Domanda

I have a basic stored procedure that adds a new record to a table with a structure like the following. The table also has a column "itemID" that is set to auto-incrementing to create a unique id for each record.

I would like to use Output to get this id from the new record I inserted and then use this to add a new record to another table (Table2 with columns colD, colE, colF). colF in Table2 should be the Output from the below as this is the id that links both tables.

Can someone here tell me how this would work as I am pretty new to SQL and have never done this before ?

My stored procedure (example):

ALTER PROCEDURE [dbo].[CreateStuff]
    @colA datetime,
    @colB varchar(50),
    @colC nvarchar(20)
AS
BEGIN
SET NOCOUNT ON;
    INSERT INTO Table1
        (
            colA,
            colB,
            colC
        )
    SELECT  @colA,
            @colB,
            @colC
END

Many thanks for any help with this, Tim.

È stato utile?

Soluzione

BEGIN  
    SET NOCOUNT ON;

    /* Here declare a Table Variable */

    DECLARE @Table_Var TABLE(itemID INT)

    INSERT INTO Table1(colA,colB,colC)
    OUTPUT inserted.itemID INTO @Table_Var(itemID)
    SELECT @colA,@colB,@colC
    
    
    /* Now do the insert into Table 2*/        
    INSERT INTO TABLE2
    SELECT itemID FROM @Table_Var
END

SCOPE_IDENTITY() is only good when you are doing a single Insert, and it is an IDENTITY column whos value you want to capture. It will only return the last Generated Identity value.

Other then that if you are doing multiple insert or it isn't an identity column then you should use OUTPUT clause along with a table variable/temp table to capture the inserted values. and then do whatever you want to do with them values later on (insert in another table/logging whatever).

To learn more about OUTPUT Clause have a look at this link.

Altri suggerimenti

Try with SCOPE_IDENTITY():

ALTER PROCEDURE [dbo].[CreateStuff]
    @colA datetime,
    @colB varchar(50),
    @colC nvarchar(20),
    @Valueout int output
AS
BEGIN
SET NOCOUNT ON;
    INSERT INTO Table1
        (
            colA,
            colB,
            colC
        )
    SELECT  @colA,
            @colB,
            @colC
SET @Valueout = SCOPE_IDENTITY()
END

You can create a Trigger on the table as follows:

    CREATE TRIGGER Trigger_Name 
       ON  Table_Name 
       AFTER INSERT,UPDATE
    AS 
    BEGIN
       SET NOCOUNT ON;

       INSERT INTO Table1 ( colA, colB, colC )
       SELECT  colA, colB, colC FROM Inserted

    END
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top