简体   繁体   English

使用Scope_Identity进行选择时出错

[英]error with select using Scope_Identity

I am trying to understand what is wrong with this select. 我试图了解此选择出了什么问题。 I want to get the last user_Id which was been added. 我想获取添加的最后一个user_Id。

Here is the error message: The parameterized query '(@Id_user int)SELECT SCOPE_IDENTITY() AS id_user' expects the parameter '@Id_user', which was not supplied. 这是错误消息:参数化查询'(@Id_user int)SELECT SCOPE_IDENTITY()AS id_user'需要未提供的参数'@Id_user'。

Here is the SQL statement: 这是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();
    }

you haven't defined an @parameter in your sql statement so you don;t need to add the parameter at all - just get the result of ExecuteScalar - you should be able to cast it to an int - although I cast it specifically in the sql statement too - 您尚未在sql语句中定义@parameter,所以您根本不需要添加参数-仅获取ExecuteScalar的结果-您应该可以将其强制转换为int-尽管我专门在sql语句-

select cast(Scope_identity() as int) ....

so you'd end up with somthing like 所以你最终会像

        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;

Even better you could create a stored procedure and have the insert done there, where it can then return scope identity. 更好的是,您可以创建一个存储过程,并在那里完成插入操作,然后在该存储过程中返回范围标识。

Edited to include example with insert. 编辑为包括带有插入示例。 (just typed in here - so likely some typos) (只需在此处输入-可能是一些错字)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM