我想插入記錄到sql server 2008表中,使用c#asp.net,列值都被聲明爲「nvarchar」,並且第一列subid是主鍵。在我的代碼中,我檢索最後一個coulmn id,遞增它並將其用作新記錄的子標識符,當我插入一條記錄時,它不會按順序存儲,而是存儲在中間的某處。因此,下次嘗試檢索最後一個id列值(儘管我使用「order by」),它給出了現有的值,當它遞增時,會給出一個錯誤,「重複值,不允許」。 這是我的代碼來檢索值的最後一個ID,並增加它:特定行後插入記錄
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();
我插入的代碼是:
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();
如何使價值得到插在最後一行,請幫助。 我的subid具有類似「IT10001」,「EC10001」的值,以便根據前兩個字母識別部門,這就是爲什麼我要使用varchar!
這種方法是一個非常可怕的設計 - 您不應該使用「SELECT MAX(..)+ 1」方法來創建新的ID值。這是**不安全**負載下 - 如果多個用戶使用此應用程序,而不是稍後您會有重複。 **不要這樣做!**在表中使用'INT IDENTITY'列,讓SQL Server爲您處理ID的唯一性。 –
@marc_s出於興趣,你每天需要告訴人們多少次? ;-) – Bridge
@Bridge:**方式太多次了!** :-( –