After two days tests on batch, roll back and try ..catch, my mind is still vague. I separate what I was doing into two step in order to clear my question.
1. roll back a batch As online book explains, in a batch, executed statements cannot be roll back only except the batch is in a transaction and error in the batch cause the transaction is roll back.
So I put the batch into a transaction like
begin transaction
create table A ...
insert into A values...
insert into A values... (error here!)
insert into A values...
GO
rollback
This works with error output and no table was created
(1 row(s) affected)
Msg 213, Level 16, State 1, Line 5
Column name or number of supplied values does not match table definition.
Msg 208, Level 16, State 1, Line 1
Invalid object name 'A'.
However, the rollback will be executed anyway even no error in transaction. In order to deal with this case, I use TRY ...CATCH as in 2.
2. use TRY ...CATCH
BEGIN TRY
begin transaction
create table A ...
insert into A values...
insert into A values... (error here!)
insert into A values...
--GO
END TRY
BEGIN CATCH
ROLLBACK
END CATCH
This time it doesn't allow statement GO here any more. S*o Batch is whole block between BEGIN TRY
AND END TRY
in this case?*
In addition, the result is not as I expected. The CREATE TABLE
AND first insert were still executed and didn't roll back.
I searched again. It seems I need to SET XACT_ABORT ON
in order to record these executed statement as uncommitted before touch commit. What I am understanding here is right? If so, I didn't add any commit statement in this case.
By the way, test are done on SQL SERVER 2012. Thanks for any clarification!