我有一个带有两个insert语句的存储过程,其中我想将第一个insert语句的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的问题,我也尝试@@IDENTITY
和IDENT_CURRENT
但不起作用。
答案 0 :(得分: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