Click here to Skip to main content
15,903,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
con.Open();

<pre><pre lang="text">
SqlCommand cmd_orderNo = new SqlCommand("SELECT IDENT_CURRENT('Oreders_Table') + IDENT_INCR('Oreders_Table')",con);
SqlDataReader dr = cmd_orderNo.ExecuteReader();
if (dr.Read())
{
Label28.Text = dr["O_number"].ToString();

}

What I have tried:

Is the above code right or not?

if it's wrong then how I can do it?
Posted
Updated 28-Feb-22 1:19am
v2

1 solution

Well ... it's right and wrong.
It'll probably work, but ... it's also probably flawed as well.

A DataReader return rows, yes - but what it is designed for is returning multiple rows - and since you are only interested in a single value, then directly using ExecuteScalar instead is a better idea.

And since you don't name your column in the SELECT statement, it';s unlikely that the DataReader indexing will work.

But the biggy is that what you seem to be doing is trying to "pre-generate" an ID number before you insert a row, and that's dangerous: SQL is a multiuser system so what works fine in development with just you testing then fails and throws up horrible intermittent data corruption problems which are a bugger to fix because two different users pre-generated the same ID and used it later.

Instead, change your DB to use an IDENTITY field as the ID, and only access that in your C# code once you INSERT the new row using the @@IDENTITY[^] variable. SQL will ensure you get unique values only.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900