Calling stored procedure from another stored procedure SQL Server

后端 未结 3 601
予麋鹿
予麋鹿 2020-12-14 00:32

I have 3 insert stored procedures each SP inserts data in 2 different tables

Table 1          Table 2                
idPerson         idProduct                      


        
相关标签:
3条回答
  • 2020-12-14 00:49

    Simply call test2 from test1 like:

    EXEC test2 @newId, @prod, @desc;
    

    Make sure to get @id using SCOPE_IDENTITY(), which gets the last identity value inserted into an identity column in the same scope:

    SELECT @newId = SCOPE_IDENTITY()
    
    0 讨论(0)
  • 2020-12-14 00:59

    You could add an OUTPUT parameter to test2, and set it to the new id straight after the INSERT using:

    SELECT @NewIdOutputParam = SCOPE_IDENTITY()
    

    Then in test1, retrieve it like so:

    DECLARE @NewId INTEGER
    EXECUTE test2 @NewId OUTPUT
    -- Now use @NewId as needed
    
    0 讨论(0)
  • 2020-12-14 01:01

    First of all, if table2's idProduct is an identity, you cannot insert it explicitly until you set IDENTITY_INSERT on that table

    SET IDENTITY_INSERT table2 ON;
    

    before the insert.

    So one of two, you modify your second stored and call it with only the parameters productName and productDescription and then get the new ID

    EXEC test2 'productName', 'productDescription'
    SET @newID = SCOPE_IDENTIY()
    

    or you already have the ID of the product and you don't need to call SCOPE_IDENTITY() and can make the insert on table1 with that ID

    0 讨论(0)
提交回复
热议问题