将一个存储过程的输出值传递给另一个存储过程

时间:2013-08-27 09:32:01

标签: sql sql-server sql-server-2008 stored-procedures merge

我想在另一个存储过程中使用一个存储过程的输出值。

存储过程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存储过程的输出选项以在下一个语句中使用它?

1 个答案:

答案 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