Can I rollback Dynamic SQL in SQL Server / TSQL -


Can I run a dynamic SQL in the transaction and roll back using EXEC:

exec (select 'from the table; select from * to tablebie;');

Place this in a transaction and use the @@ error after the Adam statement to rollback.

For example. Code

  BEGIN transfer execution (select 'from * to table; select * to tableb';); IF @@ ERROR! = 0 ROLAB Returning Returns and ELSC Commit Transaction  

If there is a dynamic SQL statement and there is an error in N / 2 then the first 1 ((n / 2) - 1) statement roll back


Questions about the first answer

@@ will not take the error error most likely, which means that it can not be possible error, which means Can there be any transaction?

TRY / CATCH in SQL Server 2005+ Yes I am using SQL Server 2005 but have not tried to catch before using

  BEGIN Start the transcription (select from 'exec; from the table; select;' tableb; ';); Command Transfer End Catch Rollback Transaction End Cache  

Or I should look at some other instances on the net

  Try BEGIN - Start the block of effort BEGIN transfer - Start Transaction .. exec ('SELECT * FROM TableA; SELECT * FROM TableB;'); Quote Tran - Transaction Success! Finally catch if @@ transcount & gt; 0 rollback tran - error RAISERROR (ERROR_MESSAGE (), ERROR_SEVERITY (), 1) END cache  

< P> Yes TXN is related to the current session / connection and the dynamic SQL uses the same reference.

However, @@ will not take the most likely error of error: the situation will immediately be checked after the abusive statement. I use TRY / CATCH, SQL Server 2005 +

EDIT: TRY / CATCH should work fine.


Comments

Popular posts from this blog

c# - How to capture HTTP packet with SharpPcap -

php - Multiple Select with Explode: only returns the word "Array" -

php - jQuery AJAX Post not working -