MSSQL SERVER COMMIT or ROLLBACK TRASACTION

USE TEST;

CREATE TABLE [dbo].[tb_TransactionTest](
[value] [int] NOT NULL,
 CONSTRAINT [PK_tb_TransactionTest] PRIMARY KEY CLUSTERED
(
[value] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

//TEST 1
BEGIN TRANSACTION
  BEGIN TRY
    PRINT 'STAT 1';
    INSERT INTO tb_TransactionTest VALUES (1);
    PRINT 'STAT 2';   
    INSERT INTO tb_TransactionTest VALUES (2);
    PRINT 'STAT 3';
    INSERT INTO tb_TransactionTest VALUES (3);
    COMMIT;
    PRINT 'COMMIT ALL';
  END TRY
  BEGIN CATCH
     ROLLBACK;
     PRINT ERROR_MESSAGE();
  END CATCH
GO

//TEST 2 (test with 1 error)
BEGIN TRANSACTION
  BEGIN TRY
    PRINT 'STAT 1';
    INSERT INTO tb_TransactionTest VALUES (1);
    PRINT 'STAT 2';
    INSERT INTO tb_TransactionTest VALUES (2);
    PRINT 'STAT 3';
    INSERT INTO tb_TransactionTest VALUES (2); -- error found
    COMMIT;
    PRINT 'COMMIT ALL';
  END TRY
  BEGIN CATCH
     ROLLBACK;
     PRINT ERROR_MESSAGE();
  END CATCH
GO

TEST #3 (test with Delphi 7 no error)
//conn: TSQLConnection;
procedure TForm1.Button1Click(Sender: TObject);
var
  TransUpdate: TTransactionDesc;
  SQLstr: TStrings;
begin
  TransUpdate.TransactionID := 1;
  TransUpdate.IsolationLevel := xilREADCOMMITTED;

  conn.StartTransaction(TransUpdate);
  SQLstr:= TStringList.create;
  try
    SQLstr.add('    INSERT INTO tb_TransactionTest VALUES (1);');
    SQLstr.add('    INSERT INTO tb_TransactionTest VALUES (2);');
    SQLstr.add('    INSERT INTO tb_TransactionTest VALUES (3); ');
  finally
   try
//     SQLQuery1.SQL.Clear;
//     SQLQuery1.SQL.Add(SQLstr.text);
//     SQLQuery1.ExecSQL(true);
     conn.ExecuteDirect(SQLstr.text);
     conn.Commit(TransUpdate);
     lbOutput.Items.Add('Success');
   except
    on e : EDatabaseError do begin
        conn.Rollback(TransUpdate);
        lbOutput.Items.add(e.message);
    end;
   end;
    SQLstr.free;
  end;
end;

TEST #4 (test with Eelphi 7 has error)

//conn: TSQLConnection;
procedure TForm1.Button1Click(Sender: TObject);
var
  TransUpdate: TTransactionDesc;
  SQLstr: TStrings;
begin
  TransUpdate.TransactionID := 1;
  TransUpdate.IsolationLevel := xilREADCOMMITTED;

  conn.StartTransaction(TransUpdate);
  SQLstr:= TStringList.create;
  try
    SQLstr.add('    INSERT INTO tb_TransactionTest VALUES (1);');
    SQLstr.add('    INSERT INTO tb_TransactionTest VALUES (2);');
    SQLstr.add('    INSERT INTO tb_TransactionTest VALUES (2); -- error found');
  finally
   try
//     SQLQuery1.SQL.Clear;
//     SQLQuery1.SQL.Add(SQLstr.text);
//     SQLQuery1.ExecSQL(true);
     conn.ExecuteDirect(SQLstr.text);
     conn.Commit(TransUpdate);
     lbOutput.Items.Add('Success');
   except
    on e : EDatabaseError do begin
        conn.Rollback(TransUpdate);
        lbOutput.Items.add(e.message);
    end;
   end;
    SQLstr.free;
  end;
end;

Comments