我是開發新手,我想將插入行的最後一個密鑰ID顯示到標籤中。我有的代碼不會將值返回到標籤中。將範圍ID的值返回到標籤
代碼,我有:
using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Users"].ConnectionString))
{
var cmd = "INSERT INTO Quote (Customer, Date)VALUES (@Customer, @Date);SELECT CAST(scope_identity() AS int)";
using (var insertCommand = new SqlCommand(cmd, conn))
{
int newID;
insertCommand.Parameters.AddWithValue("@Customer", TextBox12.Text);
insertCommand.Parameters.AddWithValue("@Date", DateTime.Now);
conn.Open();
newID = (int)insertCommand.ExecuteScalar();
Label1.Text = newID;
}
}
你有什麼看起來像它應該工作 - 從[MSDN](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar其直( v = vs.110)的.aspx)。可能嘗試在'INSERT INTO'之前添加一個'SET NOCOUNT ON'? – StuartLC