繁体   English   中英

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

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

我有一个问题,我不知道为什么会发生!

我试图在数据库表内的一列中找到最大值,我使用以下代码:

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"]));
    }
}

该代码正在运行,但是尽管表中没有记录,但给出的是1? 我使用C#和Access数据库ACCDB。

我在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;
}

请问是什么问题?

这是您的查询:

Select Max(CustomerID) AS MaxID
From TblCustomers

这是一个聚合查询。 没有group by聚合查询总是返回一行-不管是否有任何行匹配。

对于MaxId ,单行返回的值为NULL

我对您要做什么很怀疑。 如果您想要最大的id-如果表为空则没有行-请执行以下操作:

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

(这使用ANSI / ISO标准语法,因此确切的逻辑可能取决于您的数据库。)

我的怀疑是您然后想将此ID用于insert -这是一个不好的方法。 几乎所有数据库都支持某种自动递增的列(带有诸如auto_incrementserialidentity语法元素)。 这是为表中的列分配唯一的递增ID的正确方法。

如果没有符合条件的行,则Sql查询可能返回null。

如果要查找返回的行数,请更改sql查询以返回计数而不是使用聚合函数。

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

暂无
暂无

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

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