如何在visual studio 2005中使用scope_identity?

时间:2012-06-24 06:35:07

标签: asp.net sql-server scope-identity

如果我想要获取最后插入的标识,请将SELECT SCOPE_IDENTITY()语句放在何处,我将其放入查询中的其他插入内容但我什么都没得到。

SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString);

connection.Open();

string insACmd = "insert into admin (userName, password) values (@userName, @password) SELECT SCOPE_IDENTITY();";
SqlCommand insertAdmin = new SqlCommand(insACmd, connection);

insertAdmin.Parameters.AddWithValue("@userName", TextBox1.Text);
insertAdmin.Parameters.AddWithValue("@password", TextBox2.Text);

string insertedID = insertAdmin.ExecuteScalar().ToString();

connection.Close(); 

感谢。

2 个答案:

答案 0 :(得分:0)

试试这个`

  

SELECT UserId = SCOPE_IDENTITY()

如果您使用UserId作为密钥

答案 1 :(得分:0)

using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString))
{
    connection.Open();
    string insACmd = "insert into admin (userName, password) values (@userName, @password); DECLARE @ID INT OUTPUT; SET @ID=SCOPE_IDENTITY()";
    using (SqlCommand insertAdmin = new SqlCommand(insACmd, connection))
    {
        insertAdmin.Parameters.AddWithValue("@userName", TextBox1.Text);
        insertAdmin.Parameters.AddWithValue("@password", TextBox2.Text);

        SqlParameter p = new SqlParameter();
        p.ParameterName = "@ID";
        p.Size = 4;
        p.Direction = ParameterDirection.Output;
        insertAdmin.Parameters.Add(p);
        insertAdmin.ExecuteNonQuery();
        int idOut = (int)p.Value;
        connection.Close();
    }
}