0

I have two tables named user_info and food_info, user_info have an auto-incremented attribute named user_id. now I want to insert into two tables at once through a transactions like shown in the below picture, I have done this manually, now I want to achieve this through transaction query. Note that food_info's user_id is not auto-incremented.

enter image description here

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
shahtaj khalid
  • 476
  • 7
  • 24

1 Answers1

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
Sabarish
  • 64
  • 4