我想在另一个存储过程中使用一个存储过程的输出值。
存储过程1:
Create PROCEDURE [dbo].[usp_AddUpdateUser]
@UserId INT,
@Email varchar(50),
@FirstName varchar(50)
AS
BEGIN
MERGE [User] AS target
USING (SELECT @UserId) AS source (Id)
ON target.Id = source.Id
WHEN MATCHED THEN
UPDATE
SET Email = @Email,
FirstName = @FirstName
WHEN NOT MATCHED THEN
INSERT (Email, FirstName)
VALUES (@Email, @FirstName)
OUTPUT inserted.Id;
END
现在我想将上面存储过程的插入ID用于下面的存储过程:
ALTER PROCEDURE usp_AddUpdateDealer
(@Id INT,
@DealerName varchar(55),
@Email varchar(55),
@UserId INT)
AS
BEGIN
DECLARE @NewUserId INT
EXEC @NewUserId = usp_AddUpdateUser @UserId, @Email, @DealerName
MERGE Dealer AS target
USING (SELECT @Id) AS source (Id) ON target.Id = source.Id
WHEN MATCHED THEN
UPDATE
SET @DealerName = @DealerName,
Email = @Email,
UserId = @NewUserId
WHEN NOT MATCHED THEN
INSERT (DealerName, Email, UserId)
VALUES (@DealerName, @Email, @NewUserId)
OUTPUT inserted.Id;
END
@NewUserId
没有给出输出值。
如何获得usp_AddUpdateUser
存储过程的输出选项以在下一个语句中使用它?
答案 0 :(得分:1)
ALTER PROCEDURE usp_AddUpdateDealer
(
@Id INT,
@DealerName varchar(55),
@Email varchar(55),
@UserId INT
)
AS
BEGIN
DECLARE @t table(NewUserId INT )
INSERT @t(NewUserId)
EXEC @NewUserId = usp_AddUpdateUser @UserId,@Email,@DealerName
DECLARE @NewUserId INT
SELECT @NewUserId = NewUserId FROM @t
MERGE Dealer AS target
USING (SELECT @Id) AS source (Id)
ON target.Id = source.Id
WHEN MATCHED THEN
UPDATE
SET @DealerName = @DealerName,
Email = @Email,
UserId=@NewUserId
WHEN NOT MATCHED THEN
INSERT (DealerName,Email,UserId)
VALUES (@DealerName,@Email,@NewUserId)
OUTPUT inserted.Id;
END