Wednesday, March 21, 2012

primary key problem

hello!
i'm new to sql server and having some problem getting the primary key or index (Reference column). opening up the design table, the primary key or index column has an identity seed number that may vary in time. the identity increment is 1. in my code, i'm trying to get the next value and showing it in a textbox (txtReference). but i'm getting the wrong value.
example: if the last row in the table TaskOrder has a value of 150 in the Reference column, i'm getting the value of 151. but bec. of the identity seed of 200, when the row is actually added, the value for the Reference column is 201 or higher.
how do i get the actual value that the database will use? i need to change my select statement.
my code:
sReference = "Select max(Reference) From TaskOrder";
sqlConn = new SqlConnection(ConfigurationSettings.AppSettings["sql2000"]);
sqlCMD = new SqlCommand(sReference);
sqlCMD.Connection = sqlConn;
sqlConn.Open();
SqlDataAdapter adapter = new SqlDataAdapter(sqlCMD);
DataSet ds = new DataSet();
adapter.Fill(ds);
int tableRowCount = ds.Tables[0].Rows.Count;
if (tableRowCount == 1)
{
sReference = ds.Tables[0].Rows[0].ItemArray[0].ToString();
nReference = int.Parse(sReference) + 1;
sReference = nReference.ToString();
Session["sReference"] = sReference;
txtReference.Text = sReference;
}
else
{
txtReference.Text = "1";
}
sqlConn.Close();

IDENT_CURRENT('table_name') will return the last identity value inserted. If you add the increment value to it, that will be the next identity value. Please change'table_name' to actual table name you have. Please correct me if I am wrong..|||how do i use IDENT_CURRENT('TaskOrder') and identity increment in c# asp.net? do i put them in a select statement?|||You have to use in the select command as you originally wrote:
select IDENT_CURRENT('TaskOrder') from TaskOrder
Let me know if this works|||thanks a lot, Mohammad Musa. it's working now.

No comments:

Post a Comment