简体   繁体   English

数据库中没有记录时,如何获取新的ID?

[英]How to get a new id when there is no records in database?

when I run this method GetNewID() it should return max Product_Id + 1 from database. 当我运行此方法GetNewID()时,它应该从数据库中返回最大Product_Id +1。 So if the Max Product_Id in the database is 20 the next one should be 21. That's working fine. 因此,如果数据库中的最大Product_Id为20,则下一个应该为21。这很好。

But what's not working is when there is no records in database and it's null. 但是,当数据库中没有记录并且为空时,这是行不通的。 I've tried with a different select statement and some if-statements but didn't work. 我尝试了不同的select语句和一些if语句,但是没有用。 Do you have any ideas on how I can solve this problem? 您对我如何解决此问题有任何想法吗? Thanks in advance. 提前致谢。

    public static int GetNewId()
    {
        string selectString = @"SELECT MAX(Product_Id) FROM Products";
        try
        {
            newId= 0;
            connection = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=DB;Integrated Security=SSPI;");
            connection.Open();

            SqlCommand cmdSelectLastId = new SqlCommand(selectString, connection);

            newId = Convert.ToInt32(cmdSelectLastId.ExecuteScalar());

        }
        finally
        {
            if (connection != null)
            {
                connection.Close();
            }
        }

        return newId + 1;
    }

没有记录时,使查询返回零而不是null:

string selectString = @"SELECT ISNULL(MAX(Product_Id),0) FROM Products";

The simple answer is: 简单的答案是:

SELECT ISNULL(MAX(Product_Id), 0) FROM Products

However, the way in which you're implementing this is potentially fraught with danger. 但是,实施此方法的方式可能充满危险。 For example, have you considered two concurrent processes running through this code one immediately after the other, but before the record for the first has been inserted into the database? 例如,您是否考虑过两个并发进程通过该代码运行,一个紧接着另一个,但在第一个记录插入数据库之前?

Depending upon your database, you may be better off using an automatically generated ID, or a GUID. 根据您的数据库,使用自动生成的ID或GUID可能更好。

SELECT COALESCE(MAX(Product_Id), 0) FROM Products

您也可以在查询中添加1:

SELECT COALESCE(MAX(Product_Id), 0) +1 FROM Products

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

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