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

发布于 2024-11-04 06:21:06 字数 3024 浏览 0 评论 0原文

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

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(我的存储过程返回给我),或者如果用户已经存在而不是我想返回 -1

请告诉我如何做这个吗?

提前致谢 :)

I m creating new user registration moduleand for that i wrote following stored proc.

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 

And following is the simple ASP.net C# Code that I try to use

 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;
            }
        }

Through my C# code i want to return either auto generated userId which my stored procedures returns to me or if user alrady exists than i want to return -1

Please tell how to do this?

Thanks in advance :)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

白况 2024-11-11 06:21:06

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

Print '-1'

Select -1 as NewID

Yes, you can use ExecuteScalar() and change

Print '-1'

into

Select -1 as NewID
三月梨花 2024-11-11 06:21:06

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

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

当您这样做时 - 我还建议将您的 SqlConnectionSqlCommand 对象放入 using 块中 - 因此,不要使用您的代码,而是使用以下代码:

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

First of all, you should use SELECT SCOPE_IDENTITY() inside your stored proc to retrieve the new ID value (@@IDENTITY can return false results).

And yes, if you want to get the result back, you need to call either .ExecuteScalar() or .ExecuteReader() and then read that value back.

And while you're at it - I'd also recommend putting your SqlConnection and SqlCommand objects into using blocks - so instead of your code, use this:

using(con = new SqlConnection(connectionString))
using(cmd = new SqlCommand(con))
{
    ..... // put the rest of your code here
}
指尖微凉心微凉 2024-11-11 06:21:06

如果您想为存储过程创建输出参数,并将其设置为新密钥,您可以通过这种方式访问​​它。 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;

If you want to create an output parameter for your stored proc, and set it to the new key you can access it that way. ExecuteNonQuery will return the number of rows affected, so that can be used as well. Something like this:

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;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文