SQL Server 开始/结束与开始传输/提交/回滚 [英] SQL Server BEGIN/END vs BEGIN TRANS/COMMIT/ROLLBACK

查看:31
本文介绍了SQL Server 开始/结束与开始传输/提交/回滚的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图在网络上查找有关这些陈述之间差异的信息,在我看来它们是相同的,但我找不到对此的确认或两者之间的任何比较.

I have been trying to find info on the web about the differences between these statements, and it seems to me they are identical but I can't find confirmation of that or any kind of comparison between the two.

这样做有什么区别:

BEGIN
    -- Some update, insert, set statements
END

并这样做

BEGIN TRANS
    -- Some update, insert, set statements
COMMIT TRANS

?

注意只有在出现异常或超时或其他一般故障的情况下才需要回滚,不会有条件回滚.

Note that there is only the need to rollback in the case of some exception or timeout or other general failure, there would not be a conditional reason to rollback.

推荐答案

BEGIN 和 END 处理代码块.它们类似于您在许多语言中看到的花括号:

BEGIN and END deal with code blocks. They are similar to the curly braces you see in many languages:

if (somethingIsTrue)
{ // like BEGIN
    // do something here
} // like END

在 SQL 中,这是:

In SQL, this is:

if somethingIsTrue
BEGIN
    -- do something here
END

BEGIN TRANCOMMITROLLBACK 开始和结束 交易.它们不指定新的代码块;他们只标记交易边界.

BEGIN TRAN, COMMIT, and ROLLBACK begin and end transactions. They do not specify a new block of code; they only mark the transaction boundaries.

请注意,您可以在单独的代码块中编写 BEGIN TRANCOMMIT.例如,如果您希望代码成为交易的一部分,但如果代码已经在交易中,您又不想开始新的交易,则可以执行以下操作:

Note that you can write a BEGIN TRAN and COMMIT in separate blocks of code. For example, if you want code to be part of a transaction, but you don't want to start a new one if the code is already in a transaction, you can do something like this:

declare @TranStarted bit = 0
if @@trancount = 0
begin
    set @TranStarted = 1
    begin tran
end

-- ... do work ...

if @TranStarted = 1
begin
    commit
    set @TranStarted = 0
end

这篇关于SQL Server 开始/结束与开始传输/提交/回滚的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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