1

我有一个带有两个插入语句的存储过程,我想将第一个插入语句的 ID 插入第二个。

CREATE PROC [dbo].[Log_Action] 
    @action_description VARCHAR(MAX),
    @creator_id INT,
    @entity VARCHAR(50),
    @entity_identifier UNIQUEIDENTIFIER
AS
BEGIN
    DECLARE @return_value BIT;

    BEGIN TRY

        INSERT INTO Action_Lookup (action_description)
        VALUES (@action_description);

        INSERT INTO Audit ([user_id], action_id, CREATED, [guid], entity, entity_identifier)
        VALUES (@creator_id, SCOPE_IDENTITY(), GETDATE(), NEWID(), @entity, @entity_identifier);

        SET @return_value = 1;
        RETURN @return_value;

    END TRY
    BEGIN CATCH

        SET @return_value = 0;
        RETURN @return_value;

    END CATCH
END

SCOPE_IDENTITY()返回null 的问题,我也尝试过@@IDENTITYIDENT_CURRENT但不起作用。

4

1 回答 1

1

尝试output子句:

CREATE PROC [dbo].[Log_Action]
    @action_description VARCHAR(MAX),
    @creator_id INT,
    @entity varchar(50),
    @entity_identifier uniqueidentifier
AS
BEGIN
    DECLARE @return_value bit;

    BEGIN TRY

    INSERT INTO Action_Lookup (action_description)
    OUTPUT
        @creator_id,
        inserted.[id], -- in [] there should be actual name of identity column
        GETDATE(),
        NEWID(),
        @entity,
        @entity_identifier
        INTO Audit ([user_id], action_id, created, [guid], entity, entity_identifier) 
    VALUES (@action_description);

        set @return_value = 1;
        return @return_value;
    END TRY
    BEGIN CATCH
        set @return_value = 0;
        return @return_value;
    END CATCH
END
于 2013-08-04T23:04:09.413 回答