[DB] SQL SERVER

[MSSQL] commit/rollback - begin tran

mewoni 2023. 5. 22. 14:12
반응형

mssql 은 기본적으로 auto-commit mode로 되어있어 

DML(INSERT, UPDATE, DELETE) 문 실행시 commit 명령어를 추가로 입력해야 할 필요가 없다.

 

쿼리를 통한 데이터 변경 시, 잘못된 쿼리를 실행 했을 때를 위해 begin tran 이라는 명령어를 제공한다.

 

기본 문법 ) 

--Applies to SQL Server and Azure SQL Database
 
BEGIN { TRAN | TRANSACTION }   
    [ { transaction_name | @tran_name_variable }  
      [ WITH MARK [ 'description' ] ]  
    ]  
[ ; ]

 

예시 )

begin tran
update [table] set [column1] = 'data'
where [column2] = 'exdata';

commit/rollback;

SELECT 절 실행 등을 통해 충분한 데이터 검증 후, commit 또는 rollback 명령어를 실행해 준다.

 

정상 반영 시 - commit tran;

잘못 반영 시 - rollback tran;

 

*** begin transaction 을 시작할 때, 현재 transaction 분리 수준에 따라 commit/rollback 을 수행하기 전 까지 트랜잭션에 의해 잠김 상태가 되므로 DB가 정상 조회/수정/삭제 등의 수행이 되지 않는다. ***

 

begin transaction -> 데이터 검증 후 반드시 transaction을 종료해주는 것이 필요함.

 

참조 ) microsoft 공식 문서

https://learn.microsoft.com/en-us/sql/t-sql/language-elements/begin-transaction-transact-sql?view=sql-server-ver16 

 

BEGIN TRANSACTION (Transact-SQL) - SQL Server

BEGIN TRANSACTION (Transact-SQL)

learn.microsoft.com

 

반응형