Click here to Skip to main content
15,889,867 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to insert records into the sql server 2008 table,using c# asp.net,the column values are all declared as "nvarchar",and the 1st column subid is the primary key.In my code,i retrieve the last coulmn id,increment it and use it as the subid for new record,when i insert a record,it does not get stored sequentially,instead it gets stored in the middle somewhere.So the next time i try to retrieve the last id column value(though i use "order by"),it gives the existing value,which when incremented,gives an error,"duplicate values,not allowed".
this is my code to retrieve the last id value and increment it:

C#
SqlCommand myCommand = new SqlCommand("SELECT TOP 1 subid FROM subjects                         

ORDER BY subid DESC", con1);         

     reader = myCommand.ExecuteReader();
    if (reader.HasRows == false)
    {
        Label4.Text = "1";
        reader.Close();
    }
    else
    {
        while (reader.Read()) // if can read row from database
        {

            id = reader[0].ToString();

        }
        int n = Convert.ToInt32(id);
        int j = n + 1;
        Label4.Text = j.ToString();


my insert code is:
C#
SqlDataAdapter da = new SqlDataAdapter("SELECT TOP 1 * FROM subjects ORDER BY       
subid DESC", con);
SqlCommandBuilder cb = new SqlCommandBuilder(da);
DataSet ds = new DataSet("subjects");
da.Fill(ds, "subjects");
DataRow row = ds.Tables["subjects"].NewRow(); 
row["subid"] = Label4.Text;
row["dept"] = (string)Session["deptmnt"];
row["yr"] = DropDownList2.SelectedValue;
row["sem"] = DropDownList3.SelectedValue;
row["subname"] = TextBox1.Text;
row["subcode"] = TextBox2.Text;

ds.Tables["subjects"].Rows.Add(row);
da.Update(ds, "subjects");

Label10.Visible = true;
con.Close();

how do i make the value get inserted as the last row,pls help.
Posted
v2
Comments
[no name] 12-Aug-13 7:23am    
You don't. The order of the records in the database table is irrelevant. It would only be relevant when you display the records.
Simon_Whale 12-Aug-13 7:27am    
How is your primary key made up? is it an integer?
sundaram meenakshi 12-Aug-13 7:40am    
no my primary key was subid,and it was an nvarchar

1 solution

thank you all for your replies :) i tried this:
SQL
SELECT max(cast(subid as int)) FROM subjects

it worked
 
Share this answer
 
v2
Comments
Simon_Whale 12-Aug-13 11:13am    
That means your SubID column is really an integer type and you should change your database design according.

WHY? as this will say you the hassle of converting the value to an int or to a string anytime you want to manipulate the value in any way

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