how to get the next autoincrement value in sql

后端 未结 10 945
时光取名叫无心
时光取名叫无心 2020-12-16 13:21

I am creating a winform application in c#.and using sql database.

I have one table, employee_master, which has columns like Id, name, address

相关标签:
10条回答
  • 2020-12-16 13:34

    the max(id) will get you maximum number in the list pf employee_master

    e.g. id = 10, 20, 100 so max will get you 100

    But when you delete the record it must have been not 100

    So you still get 100 back

    One important reason for me to say this might be the issue because you are not using order by id in your query

    0 讨论(0)
  • 2020-12-16 13:36
     SqlConnection con = new SqlConnection("Data Source=.\SQLEXPRESS;Initial Catalog=databasename;User ID=sa;Password=123");
     con.Open();
     SqlCommand cmd = new SqlCommand("SELECT TOP(1) UID FROM InvoiceDetails ORDER BY 1 DESC", con);
    
     SqlDataReader reader = cmd.ExecuteReader();
    
     //won't need a while since it will only retrieve one row
     while (reader.Read())
     {
         string data = reader["UID"].ToString();
         //txtuniqueno.Text = data;
         //here is your data
         //cal();
         //txtuniqueno.Text = data.ToString();
         int i = Int32.Parse(data);
         i++;
         txtuid.Text = i.ToString();
      }
    
    0 讨论(0)
  • 2020-12-16 13:38

    Just a thought, if what you wanted was the last auto-number that you inserted on an already open connection try using:

    SELECT @@IDENTITY FROM...
    

    from that connection. That's the best way to keep track of what has just happened on a given connection and avoids race conditions w/ other connections. Getting the maximum identity is not generally feasible.

    0 讨论(0)
  • 2020-12-16 13:43
    select isnull((max(AddressID)+1),1) from AddressDetails
    
    0 讨论(0)
  • 2020-12-16 13:45

    If you are using Microsoft SQL Server. Use this statement to get current identity value of table. Then add your seed value which you have specified at time of designing table if you want to get next id.

    SELECT IDENT_CURRENT(<TableName>)
    
    0 讨论(0)
  • 2020-12-16 13:45

    When you delete a row from the table the next number will stay the same as it doesnt decrement in any way.

    So if you have 100 rows and you deleted row 100. You would have 99 rows but the next number is still going to be 101.

    0 讨论(0)
提交回复
热议问题