为什么SELECT SCOPE_IDENTITY()返回null?

时间:2013-08-12 03:45:55

标签: asp.net sql-server-2005

我正在尝试获取上一个Insert函数生成的ID。我对Scope和Session知之甚少。但是通过阅读博客和其他来源,我明白了,我应该使用Scope_Identity()函数。但我得到零价值。这是我的代码:

 public int InsertUser(string username, string gender, string agegroup, string email, int partnerID, string userType)
{
    try
    {
        string query = "Insert into tblUser (username,gender,agegroup,email,partnerid,usertype) values (@username,@gender,@age,@email,@partnerid,@usertype)";
        SqlCommand cmd = new SqlCommand(query, _dbConnection.getCon());
        cmd.CommandType = CommandType.Text;
        cmd.Parameters.AddWithValue("@username", username);
        cmd.Parameters.AddWithValue("@gender", gender);
        cmd.Parameters.AddWithValue("@age", agegroup);
        cmd.Parameters.AddWithValue("@email", email);
        cmd.Parameters.AddWithValue("@partnerid", partnerID);
        cmd.Parameters.AddWithValue("@usertype", userType);
        if (cmd.ExecuteNonQuery() > 0)
        {
            query = "select scope_identity() as id";
            cmd = new SqlCommand(query, _dbConnection.getCon());
            SqlDataAdapter adp = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            adp.Fill(dt);// dt is showing no value in it
            return 1;// This should return ID

        }
        else {
            return -1;
        }

    }
    catch (Exception e) {
        throw e;
    }
}

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:4)

尝试将SELECT scope_identity()附加到您的第一个查询,然后使用var identity = cmd.ExecuteScalar()而不是运行cmd.ExecuteNonQuery()来捕获身份。