在事务中执行语句 - Sql Server 2005

发布于 2024-09-03 19:54:15 字数 352 浏览 9 评论 0原文

我需要更新一个数据库,其中一些表已更改(已添加列)。我想在正确的交易中执行此操作。如果代码执行没有任何问题,那么我将提交更改,否则我将数据库回滚到其原始状态。

我想做这样的事情:

BEGIN TRANSACTION
    ...Execute some sql statements here
COMMIT TRANSACTION (When every thing goes well)
ROLLBACK TRANSACTION (When something goes wrong)

请告诉我最好的方法是什么,我知道有一个 @@TranCount 变量,但不知道它的确切用途。

谢谢。

i need to update a database where some of the table have changed (columns have been added). I want to perform this action in a proper transaction. If the code executes without any problem then i will commit the changes otherwise i will rollback the database back to its original state.

I want to do something like this:

BEGIN TRANSACTION
    ...Execute some sql statements here
COMMIT TRANSACTION (When every thing goes well)
ROLLBACK TRANSACTION (When something goes wrong)

Please tell me what is the best way to do this i know there is a @@TranCount variable but dont know its exact purpose.

Thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

荒路情人 2024-09-10 19:54:15
Begin Transaction

Alter Table dbo.MyTable
Add Col1 varchar(50)

If @@Error = 0

   Begin
    Commit Transaction
   End
Else
   Begin
    Rollback Transaction
   End

@@Error 在每个 SQL 语句后都会重置,因此您必须在执行每个语句后立即检查它以检查是否有任何错误。

Begin Transaction

Alter Table dbo.MyTable
Add Col1 varchar(50)

If @@Error = 0

   Begin
    Commit Transaction
   End
Else
   Begin
    Rollback Transaction
   End

@@Error gets reset after each SQL Statement so you must check it immediately after each statement has been executed to check for any errors.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文