[英]error with select using Scope_Identity
我試圖了解此選擇出了什么問題。 我想獲取添加的最后一個user_Id。
這是錯誤消息:參數化查詢'(@Id_user int)SELECT SCOPE_IDENTITY()AS id_user'需要未提供的參數'@Id_user'。
這是SQL語句:
if (count >= 1) /* <=== verification from the insert SQL */
{
string selectStatement = "SELECT SCOPE_IDENTITY() AS id_user";
SqlCommand selectCommand = new SqlCommand(selectStatement, sqlConnection);
selectCommand.Parameters.Add("@Id_user", SqlDbType.Int, 0, "Id_user");
int newID = (int)selectCommand.ExecuteScalar();
int User_ID = Convert.ToInt32(selectCommand.Parameters["@Id_user"].Value);
Session["Id_user"] = User_ID;
buserIdAuthenticated = true;
Session["userIdAuthenticated"] = buserIdAuthenticated;
Response.Redirect("../pages/Welcome.aspx");
}
}
catch (SqlException ex)
{
lblMessage.Text = ex.Message;
}
finally
{
sqlConnection.Close();
}
您尚未在sql語句中定義@parameter,所以您根本不需要添加參數-僅獲取ExecuteScalar的結果-您應該可以將其強制轉換為int-盡管我專門在sql語句-
select cast(Scope_identity() as int) ....
所以你最終會像
string selectStatement = "SELECT cast(SCOPE_IDENTITY() AS int)";
SqlCommand selectCommand = new SqlCommand(selectStatement, sqlConnection);
object newIDobj = (int)selectCommand.ExecuteScalar();
if(newIDobj!=null)
Session["Id_user"] = (int)newIDobj;
更好的是,您可以創建一個存儲過程,並在那里完成插入操作,然后在該存儲過程中返回范圍標識。
編輯為包括帶有插入示例。 (只需在此處輸入-可能是一些錯字)
int newID = -1;
string commandString = "insert (code, desc, numbervalue) values (@code, @desc,@numbervalue); select cast(scope_identity() as int);"
using(SqlCommand cmd = new SqlCommand(commandString))
{
try
{
cmd.Parameters.Add("@code", )
// etc
int newid=(int)(cmd.ExecuteScalar()??-1);
}
catch(Exception e)
{
// something went wrong
}
}
if(newID!=-1)
{
// do something;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.