简体   繁体   中英

SQL Server Stored Procedure SCOPE_IDENTITY() issue

I have this stored procedure and inside it as you can see I use two SCOPE_IDENTITY(); the problem is that for the second scope_identity I assign it to @status variable but when I execute the stored the OUTPUT @status variable is null but the strange thing is that the two inserts works fine.

I want to return as output of the stored the scope_identity of the second insert. Can you help me?

ALTER PROCEDURE [dbo].[sp_UserInsert]
(
@Username   nvarchar(50)=null,
@Password   nvarchar(50)=null,
@Email      nvarchar(50)=null,
@RoleId     int = 0,
@UserId     int = 0,
@typeOp     int,
@status     int = 0 OUTPUT
)   

AS
BEGIN

SET NOCOUNT ON;

if (@typeOp = 1)
/*Creazione nuovo recordo nella tabella Utenti*/
BEGIN
 if exists(select * from Gruppi where Gruppi.GroupID =@roleid)
     BEGIN
        INSERT INTO dbo.Utenti(Username,Password,Email) VALUES(@Username,@Password,@Email)
        set @UserId = SCOPE_IDENTITY()
        if (@UserId > 0)
            BEGIN
                INSERT INTO dbo.Ruoli(UserID,GroupID) VALUES(@UserId,@RoleId)

                set @status = @@rowcount
            END

     END

END


END

Now I have the problem that if I execute the stored proc from SQL Server Management Studio it works fine but If I execute the stored proc from my code works only the first insert! This is the code:

 string connectionString = ConfigurationManager.ConnectionStrings["SQLConnStr"].ConnectionString;

void SubmitNewUser_Click(Object sender, EventArgs e)
{
    string username = txtUsername.Text;
    string email = txtEmail.Text;       
    string password = txtPassword.Text;
    int ddlRoleId = Convert.ToInt32(ddlRoles.SelectedValue);

    if (!string.IsNullOrWhiteSpace(username) && !string.IsNullOrWhiteSpace(email) && !string.IsNullOrWhiteSpace(password) && ddlRoleId > 0)
    {
        if (CheckUsernameAvailability(username))
        {

            try
            {
                if (!string.IsNullOrWhiteSpace(connectionString))
                {
                    using (SqlConnection dbconn = new SqlConnection(connectionString))
                    {
                        dbconn.Open();

                        SqlCommand command = new SqlCommand("sp_UserInsert", dbconn);
                        command.CommandType = CommandType.StoredProcedure;
                        command.Parameters.AddWithValue("@Username", username);
                        command.Parameters.AddWithValue("@Password", password);
                        command.Parameters.AddWithValue("@Email", email);
                        command.Parameters.AddWithValue("@RoleId", 1);
                        command.Parameters.AddWithValue("@typeOp", 1);
                        command.ExecuteNonQuery();

                        dbconn.Close();
                    }
                }
            }

            catch (Exception ex)
            {
                // Add error handling here for debugging.
                // This error message should not be sent back to the caller.
                System.Diagnostics.Trace.WriteLine("[ValidateUser] Exception " + ex.Message);
            }
        }
    }
}

As far as I understand, you don't have an identity in your second table. I think, that User_ID, Group_Id is unique key in your table, so you can just use

select * from dbo.Ruoil where User_ID = @User_ID and Group_ID = @RoleId

If you want just check if there's some rows affected, you can use @@rowcount

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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