简体   繁体   English

Datatable rows.count == 0给出1,尽管表中没有找到记录

[英]Datatable rows.count == 0 gives 1 although there not found records in the table

I have a problem and I don't know why it's happening! 我有一个问题,我不知道为什么会发生!

I am trying to find Max value in a column inside the database table, I use this code: 我试图在数据库表内的一列中找到最大值,我使用以下代码:

private void FrmCustomer_New_Load(object sender, EventArgs e)
{
    int NewID;           
    DataTable _Dt = CusVar.GetCustomersIDs();
    if (_Dt.Rows.Count == 0)
    {
        NewID = 1;
        this.txt1.Text = NewID.ToString();
        DataRow _Row = CusVar.GetCustomersIDs().Rows[0];
        MessageBox.Show(Convert.ToString(_Dt.Rows[0]["MaxID"]));
    }
}

the code is working but it gives 1 although there are no records in the table? 该代码正在运行,但是尽管表中没有记录,但给出的是1? I use C# and Access database ACCDB. 我使用C#和Access数据库ACCDB。

I use this function in Cls_Customers: 我在Cls_Customers中使用此功能:

public DataTable GetCustomersIDs()
{
    DAL.DataAccessLayer DAL = new DAL.DataAccessLayer();
    DataTable Dt = new DataTable();
    Dt = DAL.DataSelect("Select Max(CustomerID) AS MaxID From TblCustomers", null);
    DAL.CloseConn();
    return Dt;
}

what is the problem, please? 请问是什么问题?

This is your query: 这是您的查询:

Select Max(CustomerID) AS MaxID
From TblCustomers

It is an aggregation query. 这是一个聚合查询。 Aggregation queries with no group by always return one row -- regardless of whether any rows match. 没有group by聚合查询总是返回一行-不管是否有任何行匹配。

The value returned in the single row is NULL for MaxId . 对于MaxId ,单行返回的值为NULL

I am highly suspicious of what you want to do. 我对您要做什么很怀疑。 If you want the maximum id -- and no rows if the table is empty -- then do: 如果您想要最大的id-如果表为空则没有行-请执行以下操作:

select c.CustomerID
from TblCustomers c
order by c.CustomerID desc
fetch first 1 row only;

(This uses ANSI/ISO standard syntax so the exact logic might depend on your database.) (这使用ANSI / ISO标准语法,因此确切的逻辑可能取决于您的数据库。)

My suspicion is that you then want to use this id for an insert -- and that is a bad approach. 我的怀疑是您然后想将此ID用于insert -这是一个不好的方法。 Almost all databases support some sort of auto-incremented column (with syntax elements such as auto_increment , serial , or identity ). 几乎所有数据库都支持某种自动递增的列(带有诸如auto_incrementserialidentity语法元素)。 That is the right way to assign a unique incrementing id to a column in a table. 这是为表中的列分配唯一的递增ID的正确方法。

The Sql query might be returning null and if there are no rows that match the criteria. 如果没有符合条件的行,则Sql查询可能返回null。

If the intention is to find the number of rows returned.Change the sql query to return the count instead of using aggregate function. 如果要查找返回的行数,请更改sql查询以返回计数而不是使用聚合函数。

尝试使用此方法:从TblCustomers T1中选择MAX(T1.CustomerID)AS MaxID

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM