2017-01-11 100 views
0

我有兩個名爲user_info和food_info的表,user_info有一個名爲user_id的自動遞增屬性。現在我想通過下圖所示的事務一次性插入兩個表中,我已經手動完成了這一步,現在我想通過事務查詢來實現此目的。 注意 food_info的user_id不是自動遞增的。如何將自動遞增的ID傳遞到另一個表

enter image description here

+0

可能重複http://stackoverflow.com/questions/4565195/mysql-how-to-insert-into-multiple-tables-with-foreign-keys –

+0

你使用MySQL或MS SQL Server? (不要標記不涉及的產品。) – jarlh

回答

0
-- Declare Variables 
DECLARE @ErrorMessage NVARCHAR(4000), 
    @ErrorSeverity INT, 
    @ErrorState INT, 
    @Last_Inserted_ID INT; 

-- Try Catch Block 
BEGIN TRY 

-- Start Transaction 
    BEGIN TRANSACTION 
    INSERT INTO [dbo].[user_info] 
      ([user_name] 
      ,[pass]) 
     VALUES 
       ('U11' 
       ,'U12') 

    -- Returns the last identity value inserted 
    SET @Last_Inserted_ID = @@IDENTITY; 

    INSERT INTO [dbo].[food_info] 
       ([user_id] 
       ,[food_type]) 
     VALUES 
       (@Last_Inserted_ID 
       ,'Food1') 

    PRINT 'Values inserted successfully...' 

COMMIT TRANSACTION 
END TRY 
BEGIN CATCH 
    SELECT 
     @ErrorMessage = ERROR_MESSAGE(), 
     @ErrorSeverity = ERROR_SEVERITY(), 
     @ErrorState = ERROR_STATE(); 

    RAISERROR (
     @ErrorMessage, 
     @ErrorSeverity, 
     @ErrorState  
     ); 
    ROLLBACK TRANSACTION 
END CATCH