【发布时间】:2013-08-14 04:58:17
【问题描述】:
我有这个存储过程,如你所见,我在其中使用了两个 SCOPE_IDENTITY();问题是,对于第二个 scope_identity,我将其分配给 @status 变量,但是当我执行存储时,OUTPUT @status 变量为空,但奇怪的是这两个插入工作正常。
我想将第二次插入的 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);
}
}
}
}
【问题讨论】:
-
你确定你在若丽表中有身份吗?
-
你说得对,我在这张表中没有身份!那么如何返回第二次插入的受影响行数?
-
我认为你需要使用
SELECT而不是SET:SELECT @Status = SCOPE_IDENTITY() -
现在我有一个问题,如果我从 sql server managment Studio 执行存储它工作正常,但如果我从我的代码执行存储只工作第一次插入!代码见我的第一篇文章
-
我知道这是一个很老的问题,但它刚刚被编辑过,所以请引起我的注意。请注意
CREATE PROCEDURE:“在命名过程时避免使用sp_前缀。SQL Server使用此前缀来指定系统过程。使用前缀可能会导致应用程序代码中断是同名的系统过程。”
标签: sql asp-classic insert output procedure