繁体   English   中英

SQL Server中的事务

[英]Transaction in SQL Server

我是SQL的新手,遇到了问题。 假设我有一个银行的数据库,其中包含一个名为accounts的类别。 我的身份证号码1的人有1000美元,身份证号码2的人有700美元。 我想在1步之间进行交易。 我尝试执行以下操作:

update accounts
set balance = balance + 100 
where id = 2; 

set balance = balnce - 100 
where id = 3

发生的情况是2号帐户损失了100美元,而3号帐户却什么也没有。 我如何一遍又一遍地做这样的事情,以确保之间没有任何交易?

谢谢

您可以一步完成此操作:

update accounts
    set balance = (case when id = 2 then balance + 100 
                        when id = 3 then balance - 100
                        else balance
                   end)
    where id in (2, 3);

这是ANSI标准的语法,大多数(如果不是全部)数据库应“全部或全部”执行它-也就是说,两个更新都不会生效。

您需要使用交易。 交易不是一件容易的事,它可能需要一些时间,因此我建议您从文档中阅读有关交易的知识。 特别是关系数据库的ACID属性。

对于SQL Server,基本步骤是:

BEGIN TRY

    BEGIN TRANSACTION -- Start your transaction here

    /* 
        You can do these 2 operations on the same statement in this case but I
        believe you want to learn the concept
    */

    update accounts
    set balance = balance + 100
    where id = 2

    update accounts
    set balance = balance - 100
    where id = 3

    -- Do other operations like INSERTS, DELETES, etc.

    COMMIT -- You apply your changes here. From this point it will be visible to other users and will be persisted.

END TRY

BEGIN CATCH -- If something went wrong...

    IF @@TRANCOUNT > 0 -- ... and the transaction is still open
        ROLLBACK -- revert all the operations done from the point of "BEGIN TRANSACTION" statement onwards

    RAISERROR('Something went horribly wrong!', 15, 1)

END CATCH

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM