如何修改存储过程或ASP.net代码以在插入新行后获取自动生成的ID

时间:2011-04-30 13:54:37

标签: c# asp.net sql-server sql-server-2008 stored-procedures

我正在创建新的用户注册模块,为此我编写了以下存储过程。

PROCEDURE [dbo].[addNewUser]
    -- Add the parameters for the stored procedure here
    @usertype VarChar(10),
    @useremail VarChar(70),
    @userpass VarChar(20),
    @fullname VarChar(70),
    @city VarChar(70),
    @state Int,
    @allowAlerts Bit,
    @allowLetter Bit,
    @aboutMe NVARCHAR(160)

As
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;


   if ((select count(user_info._id) from user_info where useremail like @useremail)  =  0)
    BEGIN
        Insert Into user_info
        (usertype,useremail,userpass,fullname,city,[state],allowAlerts,allowLetters,aboutMe)
           Values
           (
                @usertype,
                @useremail,
                @userpass ,
                @fullname,
                @city,
                @state,
                @allowAlerts,
                @allowLetter,
                @aboutMe
            )
        Select @@IDENTITY as NewID  
    END
    Else
    BEGIN
         Print '-1'         
    END 

以下是我尝试使用的简单ASP.net C#代码

 public int registerNewUser(string usertype, string useremail, string userpass, string fullname, string city, string state, string allowAlerts, string allowLetter, string aboutMe)
        {
            con = new SqlConnection(connectionString);
            cmd = new SqlCommand();
            cmd.Connection = con;
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "addBlogEntry";
            cmd.Parameters.Add("@usertype", SqlDbType.VarChar).Value = usertype;
            cmd.Parameters.Add("@useremail", SqlDbType.VarChar).Value = useremail;
            cmd.Parameters.Add("@userpass", SqlDbType.VarChar).Value = userpass;
            cmd.Parameters.Add("@fullname", SqlDbType.VarChar).Value = fullname;
            cmd.Parameters.Add("@city", SqlDbType.VarChar).Value = city;
            cmd.Parameters.Add("@state", SqlDbType.VarChar).Value = Convert.ToInt16(state);
            cmd.Parameters.Add("@allowAlerts", SqlDbType.VarChar).Value = Convert.ToInt16(allowAlerts);
            cmd.Parameters.Add("@allowLetter", SqlDbType.VarChar).Value = Convert.ToInt16(allowLetter);
            cmd.Parameters.Add("@aboutMe", SqlDbType.VarChar).Value = aboutMe;
            try
            {
                if (con.State != ConnectionState.Open)
                    con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
                con.Dispose();

                // some code to be written here so that i can return userID(success) or -1(if that username is already registered)
                 return 0;
            }
            catch (Exception Ex)
            {
                con.Close();
                con.Dispose();

                return 0;
            }
        }

通过我的C#代码,我想返回自动生成的userId,我的存储过程返回给我,或者如果用户alrady存在而不是我想返回-1

请告诉我该怎么做?

提前致谢:)

3 个答案:

答案 0 :(得分:2)

是的,您可以使用ExecuteScalar()并更改

Print '-1'

进入

Select -1 as NewID

答案 1 :(得分:2)

首先,您应该在存储过程中使用SELECT SCOPE_IDENTITY()来检索新的ID值(@@IDENTITY可以返回错误的结果)。

是的,如果您想要获得结果,则需要调用.ExecuteScalar().ExecuteReader()然后再读取该值。

虽然您正在使用它 - 我还建议您将SqlConnectionSqlCommand个对象放入使用块中 - 所以请使用此代码而不是您的代码:

using(con = new SqlConnection(connectionString))
using(cmd = new SqlCommand(con))
{
    ..... // put the rest of your code here
}

答案 2 :(得分:0)

如果要为存储过程创建输出参数,并将其设置为新密钥,则可以通过该方式访问它。 ExecuteNonQuery将返回受影响的行数,因此也可以使用。像这样:

cmd.Parameters.Add("@uniquID", SqlDbType.Int).Direction = ParameterDirection.Output;

// Your other code...

var result = cmd.ExecuteNonQuery();

// Your other code...

return (result == 1) ? (int)cmd.Parameters["@uniquID"].Value : -1;