SQL Server在存储过程中编写事务处理代码的三种方法
2023-03-31 11:05:45 时间
SQL Server中数据库事务处理是相当有用的,鉴于很多SQL初学者编写的事务处理代码存往往存在漏洞,本文我们介绍了三种不同的方法,举例说明了如何在存储过程事务处理中编写正确的代码。希望能够对您有所帮助。
在编写SQL Server 事务相关的存储过程代码时,经常看到下面这样的写法:
- begin tran
- update statement 1 ...
- update statement 2 ...
- delete statement 3 ...
- commit tran
这样编写的SQL存在很大隐患。请看下面的例子:
- create table demo(id int not null)
- go
- begin tran
- insert into demo values (null)
- insert into demo values (2)
- commit tran
- go
执行时会出现一个违反not null 约束的错误信息,但随后又提示(1 row(s) affected)。 我们执行select * from demo 后发现insert into demo values(2) 却执行成功了。 这是什么原因呢? 原来 SQL Server在发生runtime 错误时,默认会rollback引起错误的语句,而继续执行后续语句。
如何避免这样的问题呢?有三种方法:
1. 在事务语句最前面加上set xact_abort on
- set xact_abort on
- begin tran
- update statement 1 ...
- update statement 2 ...
- delete statement 3 ...
- commit tran
- go
当xact_abort 选项为on 时,SQL Server在遇到错误时会终止执行并rollback 整个事务。
2. 在每个单独的DML语句执行后,立即判断执行状态,并做相应处理。
- begin tran
- update statement 1 ...
- if @@error <> 0
- begin rollback tran
- goto labend
- end
- delete statement 2 ...
- if @@error <> 0
- begin rollback tran
- goto labend
- end
- commit tran
- labend:
- go
3. 在SQL Server 2005中,可利用 try...catch 异常处理机制。
- begin tran
- begin try
- update statement 1 ...
- delete statement 2 ...
- endtry
- begin catch
- if @@trancount > 0
- rollback tran
- end catch
- if @@trancount > 0
- commit tran
- go
下面是个简单的存储过程,演示事务处理过程。
- create procedure dbo.pr_tran_inproc as begin set nocount on
- begin tran
- update statement 1 ...
- if @@error <> 0
- begin rollback tran
- return -1 end
- delete statement 2 ...
- if @@error <> 0
- begin rollback tran
- return -1
- end commit tran
- return 0
- end
- go
关于SQL Server数据库中在存储过程中编写正确的事务处理代码的方法就介绍到这里了,希望本次的介绍能够对您有所帮助。
原文出处:http://www.sqlstudy.com/sql_article.php?id=2008060701。
【编辑推荐】
相关文章
- Python中的函数与方法 以及Bound Method和Unbound Method
- 一文贯通python文件读取
- Python 中的异步编程:Asyncio
- 7个你现在就该学习Python的理由
- 提高Python运行效率的六个窍门
- Python数据科学:神经网络
- 一篇文章看懂大数据分析就业前景及职能定位
- R和Python中的文本挖掘:8个入门小贴士
- 告诉你为什么Python有点慢,但我却无所谓?
- 专注学习DevOps编程语言Top 5推荐
- Python发送邮件脚本
- Python多进程并行编程实践: mpi4py 的使用
- Python语言在未来的发展前景
- Python vs Ruby: 谁是最好的 web 开发语言?
- Python对Ruby:谁在Web开发领域更胜一筹?
- Python一行代码完成并行任务
- Python开发者2017应该关注的七个类库
- python爬虫入门基本知识
- 在终端中优雅地编写Python
- Python机器学习实战:信用卡欺诈检测