Connecting Tech Pros Worldwide Help | Site Map

C# How to get the next value of identity(1,1) from database table before any insert?

Newbie
 
Join Date: Jul 2008
Posts: 16
#1: 2 Weeks Ago
Hi!

Every time when I want to add a row, I call this method in the code snippet to get the next identity value.

Code Snippet:
Expand|Select|Wrap|Line Numbers
  1. private int GetNextRowID()
  2. {
  3. int NextRowID =0; 
  4.  
  5. try
  6.  
  7. using (SqlConnection ConnectionSql = new SqlConnection(ConnectionString))
  8. {
  9. StringBuilder SqlQuery = new StringBuilder();
  10.  
  11. SqlQuery.Append("USE [ExampleDatabase]; ");
  12.  
  13. // Returns 1 so works for first insert when the table is empty before any insert:
  14. // Returns 1 again for second insert, so it FAILS:
  15. SqlQuery.Append("SELECT ISNULL(IDENT_CURRENT('ExampleTable'), 0) ; "); 
  16.  
  17. SqlCommand CommandSql = new SqlCommand(SqlQuery.ToString(), ConnectionSql);
  18.  
  19. ConnectionSql.Open();
  20.  
  21. SqlDataReader DataReaderSql = CommandSql.ExecuteReader();
  22.  
  23. while (DataReaderSql.Read())
  24. {
  25. NextRowID = int.Parse(DataReaderSql.GetValue(0).ToString());
  26. }
  27.  
  28. ConnectionSql.Close();
  29.  
  30. MessageBox.Show("Add Row.");
  31. }
  32. }
  33. catch (Exception ex)
  34. {
  35. MessageBox.Show(ex.ToString());
  36. }
  37. return NextRowID;
  38. }
  39.  
SQL:
Expand|Select|Wrap|Line Numbers
  1. USE [master]
  2. GO
  3.  
  4. IF EXISTS (SELECT name FROM sys.databases WHERE name = 'ExampleDatabase') 
  5. DROP DATABASE [ExampleDatabase]; 
  6. GO
  7.  
  8. CREATE DATABASE [ExampleDatabase]; 
  9. GO
  10.  
  11. USE [ExampleDatabase]; 
  12. GO
  13.  
  14. IF EXISTS (SELECT NAME FROM SYS.TABLES WHERE NAME = 'ExampleTable') 
  15. DROP TABLE dbo.ExampleTable; 
  16. GO
  17.  
  18. CREATE TABLE 
  19. dbo.ExampleTable
  20. (
  21. ID INT IDENTITY(1,1) NOT NULL, 
  22. Name NVARCHAR(50) NULL 
  23. );
  24. GO
  25.  
  26. SELECT * FROM dbo.ExampleTable;
  27. GO
  28.  
  29. --SAME AS AFTER INSERTING:
  30. SELECT ISNULL(IDENT_CURRENT('ExampleTable'), 0) ;
  31. GO
  32.  
  33. INSERT INTO ExampleTable
  34. VALUES
  35. (
  36. 'Bill'
  37. );
  38. GO
  39.  
  40. SELECT * FROM dbo.ExampleTable;
  41. GO
  42.  
  43. --SAME AS BEFORE INSERTING:
  44. SELECT ISNULL(IDENT_CURRENT('ExampleTable'), 0) ;
  45. GO
  46.  
Plater's Avatar
Moderator
 
Join Date: Apr 2007
Location: New England
Posts: 7,148
#2: 2 Weeks Ago

re: C# How to get the next value of identity(1,1) from database table before any insert?


IDENT_CURRENT returns the LAST identity used, not the next.
Try adding 1
Reply