如果要在Production执行数据改动必须小心,可以使用事务提前验证一下自己写的SQL是不是你期望的。尤其是Update的where 条件有问题的话,跟新的记录就会超出预期的范围。如下面的语句,一着急我差点把cartid = 678417 忘了,要是在Production执行影响就大了。
BEGIN TRANSACTION update cartitem set deleted=0 where cartid = 678417 and modifieddate > '2014-08-07' select * from cartitem where cartid = 678417 order by modifieddate desc ROLLBACK TRANSACTION
下面语句实现begin tran 和commit tran之间的语句,任一如果出现错误,所有都不执
set XACT_ABORT ON ---如果不设置该项为ON,在sql中默认为OFF,那么只只回滚产生错误的 Transact-SQL 语句;设为ON,回滚整个事务 begin tran t1 ---启动一个事务 update cartitem set deleted=0 where cartid = 678417 and modifieddate > '2014-08-07'
delete from [Order] where Id=2103264408
commit tran t1 ---提交事务
事务的try, Catch
BEGIN TRY
BEGIN TRANSACTION
insert into dbo.area values('1111')
insert into dbo.area values('2222')
select 1/0
insert into dbo.area values('333')
COMMIT
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int
SELECT @ErrMsg = ERROR_MESSAGE(),
@ErrSeverity = ERROR_SEVERITY() RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH