我有这个存储过程并在其中,你可以看到我使用两个SCOPE_IDENTITY();问题是,对于第二个scope_identity,我将它分配给@status变量,但是当我执行存储时,OUTPUT @status变量为null,但奇怪的是两个插入工作正常。
我想返回存储的第二个插入的scope_identity的输出。你能救我吗?
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
现在我遇到的问题是,如果我从SQL Server Management Studio执行存储过程,它可以正常工作,但如果我从我的代码执行存储过程仅工作第一次! 这是代码:
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);
}
}
}
}
答案 0 :(得分:0)
据我了解,您的第二张表中没有身份证明。我认为,User_ID,Group_Id是表中的唯一键,因此您可以使用
select * from dbo.Ruoil where User_ID = @User_ID and Group_ID = @RoleId
如果您只想检查某些行是否受影响,可以使用@@rowcount