我在sqlcommand中使用SQL查询与 SELECT SCOPE_IDENTITY()。这是我的代码:
SqlCommand cmd = new SqlCommand("INSERT INTO tbl_Supplier(Supplier_Name,Supplier_Address, Supplier_PhoneNo,Supplier_City,Supplier_Remarks) VALUES('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','"+DropDownList1.SelectedItem+"','"+TextBox4.Text+"') RETURN SCOPE_IDENTITY()", conn);
var id = cmd.ExecuteScalar();
conn.Close();
但代码总是返回1?
答案 0 :(得分:4)
您使用错误的语法来获取该信息。
"...; SELECT SCOPE_IDENTITY()"
(另请注意SELECT之前和第一个sql语句结束后的分号)
此时ExecuteScalar能够获取SELECT返回的第一行的第一列
说,请花点时间学习如何执行"Parameterized Queries"您的代码非常弱并且是Sql Injection的简单目标
string cmdText = @"INSERT INTO tbl_Supplier
(Supplier_Name,
Supplier_Address,
Supplier_PhoneNo,
Supplier_City,
Supplier_Remarks)
VALUES(@name, @address, @phone, @city, @remarks);
SELECT SCOPE_IDENTITY()"
using(SqlCommand cmd = new SqlCommand(cmdText, connection))
{
connection.Open();
cmd.Parameters.Add("@name", SqlDbType.NVarWChar).Value = TextBox1.Text;
cmd.Parameters.Add("@address", SqlDbType.NVarWChar).Value = TextBox2.Text;
cmd.Parameters.Add("@phone", SqlDbType.NVarWChar).Value = TextBox3.Text;
cmd.Parameters.Add("@city", SqlDbType.NVarWChar).Value = DropDownList1.SelectedItem
cmd.Parameters.Add("@remarks", SqlDbType.NVarWChar).Value = TextBox4.Text;
var id = cmd.ExecuteScalar();
}
conn.Close();