473,397 Members | 1,960 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,397 software developers and data experts.

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

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.  
Nov 6 '09 #1
1 3481
Plater
7,872 Expert 4TB
IDENT_CURRENT returns the LAST identity used, not the next.
Try adding 1
Nov 6 '09 #2

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: (Pete Cresswell) | last post by:
This doesn't work because the first INSERT is creating multiple records for multiple projects. @@IDENTITY, then, contains the Identity column value for the last tblWeekReportedLine record...
10
by: salamol | last post by:
I has a strange question. My company is using a old system with Win NT 4.0 Server + MS SQL 7.0. The system is busy and handle a lot of SELECTs and INSERTs all the time. Sometimes, some...
3
by: Alex | last post by:
I have a "source" table that is being populated by a DTS bulk import of a text file. I need to scrub the source table after the import step by running appropriate stored proc(s) to copy the source...
3
by: isaacrajan | last post by:
Hello, How do I get SQL server 2000 to continue the sequence of identity column values after I perform an insert into the table with the set identity_insert <table name> on statement? Eg if I...
1
by: SAN CAZIANO | last post by:
how can clear an html SELECT and next insert in it all the elements of an array () I try this but seems doesn't works. function ComboAddArrayValueWithLabel(combo,ArrayLabel,ArrayValue) { ...
3
by: tlyczko | last post by:
I have this code in a form input box contained in the 4th column cell of a 4-column table: onblur = "if (testExp(this.value, 'message') == false) {window.focus(); this.focus();}" testExp...
1
by: ddice | last post by:
I need to update and then read a sequence number, but I think its failing when there are many users updating at the same time. Here's what I'm doing update datatable set nextnr = nextnr+1 where...
6
by: jx2 | last post by:
i've got one "simple" question :) this doesnt work but i am sure u know what i mean :-) INSERT INTO table1 set no=MAX(no)+1; this doesnt work too :( insert into table1 set no=(select MAX(no)...
1
by: fran7 | last post by:
Hi, I have this code to randomly select an image from a sequence of fields in my database. Does anyone know if rather than random, one could simply move from one field to the next sequentialy. That...
1
by: kollurisaritha | last post by:
Hi I have 2 tables like Searchtable ----------------- searchid name ----------- -------- s1 chandu s2 sony
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.