简体   繁体   中英

Try Catch in SQL Server Query

How can I?

Statement 1:

UPDATE Members 
SET Count = Count - 1 
WHERE Count > 0;

Statement 2:

INSERT INTO Sessions (Name, Etc) 
VALUES('Mike', 'Other')

if statement 1 and 2 both succeed then return the newly inserted row id.

SELECT SCOPE_IDENTITY(); 

If either statement 1 or 2 fails I would like to rollback the transaction and return 0 or -1.

How can I structure this? Any help would be appreciated.

SET XACT_ABORT ON

BEGIN TRY

    BEGIN TRANSACTION

    UPDATE [Members]
    SET [Count] = [Count] - 1 WHERE [Count] > 0;

    INSERT INTO [Sessions] ([Name], [Etc])
    VALUES ('Mike', 'Other')

    COMMIT TRANSACTION

END TRY
BEGIN CATCH

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;

    RETURN 0

END CATCH

SELECT SCOPE_IDENTITY();

Here is the relevant MSDN documentation:

You can do the following

     Begin Try
        Begin tran 
           SQL logic
        Commit tran
     END try
     Begin Catch
        rollback tran            
        return 0 or -1
     end Catch

This is obviously just the structure like you ask but you can go here and get more information on the syntax, and more examples http://msdn.microsoft.com/en-us/library/ms175976.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM