通常情况下,我们使用@@ERROR全局变量来返回最后执行的Transact-SQL语句的执行情况,如果执行成功,则返回0,否则返回大于0的错误代码,例:
drop table score
print @@error
go先执行删除表score的命令,然后用@@ERROR来查看是否执行成功但如果系统在执行这个批处理时,也在并行执行由另一个客户端发送过来的一个批处理:
delete from student where sex='男'
go并且执行顺序是:(1)drop table score
(2)delete from student where sex='男'
(3)print @@error那么这时候,@@error并不是返回drop table score语句的执行情况,而是反映的delete from语句的执行情况,这就违反了当时我们编程的初忠!期待高人指点,谢谢!
drop table score
print @@error
go先执行删除表score的命令,然后用@@ERROR来查看是否执行成功但如果系统在执行这个批处理时,也在并行执行由另一个客户端发送过来的一个批处理:
delete from student where sex='男'
go并且执行顺序是:(1)drop table score
(2)delete from student where sex='男'
(3)print @@error那么这时候,@@error并不是返回drop table score语句的执行情况,而是反映的delete from语句的执行情况,这就违反了当时我们编程的初忠!期待高人指点,谢谢!
(1)drop table score set @errID=@@error if @errID<>0 goto error
(2)delete from student where sex='男' set @errID=@@error if @errID<>0 goto error
return
(3)print '@errID:'+rtrim(@errID)
@@ERROR 检测几条语句的成功
下面的示例取决于 INSERT 和 DELETE 语句的成功操作。局部变量在两条语句后均被设置为 @@ERROR 的值,并且用于此操作的共享错误处理例程中。USE pubs
GO
DECLARE @del_error int, @ins_error int
-- Start a transaction.
BEGIN TRAN-- Execute the DELETE statement.
DELETE authors
WHERE au_id = '409-56-7088'-- Set a variable to the error value for
-- the DELETE statement.
SELECT @del_error = @@ERROR-- Execute the INSERT statement.
INSERT authors
VALUES('409-56-7008', 'Bennet', 'Abraham', '415 658-9932',
'6223 Bateman St.', 'Berkeley', 'CA', '94705', 1)
-- Set a variable to the error value for
-- the INSERT statement.
SELECT @ins_error = @@ERROR-- Test the error values.
IF @del_error = 0 AND @ins_error = 0
BEGIN
-- Success. Commit the transaction.
PRINT "The author information has been replaced"
COMMIT TRAN
END
ELSE
BEGIN
-- An error occurred. Indicate which operation(s) failed
-- and roll back the transaction.
IF @del_error <> 0
PRINT "An error occurred during execution of the DELETE
statement." IF @ins_error <> 0
PRINT "An error occurred during execution of the INSERT
statement." ROLLBACK TRAN
END
GO
@@error是每次执行都会有个新值的!
学习
你的思路是通过事务来确保@@error变量被隔离开来,
但我还有些疑问:如果我的数据库同时有几千个客户端相连,并发量很大的话,按照你的思路,是不是只要用到@@error变量的话,就都用事务来解决??这样的话会不会影响到系统的性能?