正确使用SQL Server 2008中的事务 [英] Correct use of transactions in SQL Server 2008

查看:318
本文介绍了正确使用SQL Server 2008中的事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个命令,需要两个命令正确执行或不执行。
所以我想我需要一个事务,但我不知道如何正确使用它。

I have 2 commands and need both of them executed correctly or none of them execute. So I think I need a Transaction but I don't know how to use it correctly.

下面的脚本有什么问题?

What's the problem with the following script?

BEGIN TRANSACTION [Tran1]

INSERT INTO [Test].[dbo].[T1]
    ([Title], [AVG])
VALUES ('Tidd130', 130), ('Tidd230', 230)

UPDATE [Test].[dbo].[T1]
  SET [Title] = N'az2' ,[AVG] = 1
  WHERE [dbo].[T1].[Title] = N'az'

COMMIT TRANSACTION [Tran1]
GO

insert 命令已执行,但 update 命令有问题。

The insert command executed but the update command has a problem. How can I implement this to rollback both commands if any of them have an error in execution?

推荐答案

添加一个try / catch块,如果事务成功,它将提交更改,如果事务失败,事务回滚:

Add a try/catch block, if the transaction succeeds it will commit the changes, if the transaction fails the transaction is rolled back:

BEGIN TRANSACTION [Tran1]

BEGIN TRY

INSERT INTO [Test].[dbo].[T1]
  ([Title], [AVG])
VALUES ('Tidd130', 130), ('Tidd230', 230)

UPDATE [Test].[dbo].[T1]
  SET [Title] = N'az2' ,[AVG] = 1
WHERE [dbo].[T1].[Title] = N'az'


COMMIT TRANSACTION [Tran1]

END TRY
BEGIN CATCH
  ROLLBACK TRANSACTION [Tran1]
END CATCH  

GO

这篇关于正确使用SQL Server 2008中的事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆