简体   繁体   中英

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. So if the Max Product_Id in the database is 20 the next one should be 21. That's working fine.

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. 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.

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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