2013-08-04 62 views
1

我有一個存儲過程有兩個插入語句,我想在第二個插入語句的ID中插入第一個插入語句的ID。從以前的插入語句獲取最後一個插入的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()返回空的問題,我也試過@@IDENTITYIDENT_CURRENT但非作品。

+0

你確定表Action_Lookup您的ID列被聲明爲身份? – Ricardo

+0

@Ricardo是的,它是身份。 –

+0

您是否嘗試在插入到Action_Lookup後將身份值放入變量中,然後使用此變量的值?或者''Action_Lookup'表上有觸發器嗎? –

回答

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 
+0

我試過了,我得到了這個錯誤「OUTPUT INTO子句的目標表'審計'不能在任何一個發現引用約束「FK__Audit__action_id__19DFD96B」,這是真實的,表中的action_id審計引用表中的id Action_Lookup –

+0

啊,我明白了,這是有道理的。 –