通常情况下,我们使用@@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语句的执行情况,这就违反了当时我们编程的初忠!期待高人指点,谢谢!

解决方案 »

  1.   

    每个 Transact-SQL 语句执行完毕时,@@ERROR 都会得到一个新的值,可以如下形式declare @errID int
    (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)
      

  2.   

    只能把每次执行后@@error保存在变量中,然后做判断
      

  3.   

    bol的例子
    @@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
      

  4.   

    呵呵...
    @@error是每次执行都会有个新值的!
      

  5.   

    happydreamer 的写法,看得最明了
    学习
      

  6.   

    @@error执行最后一次执行错误的错误代码。。
      

  7.   

    to happydreamer(重返csdn):非常感谢你!
    你的思路是通过事务来确保@@error变量被隔离开来,
    但我还有些疑问:如果我的数据库同时有几千个客户端相连,并发量很大的话,按照你的思路,是不是只要用到@@error变量的话,就都用事务来解决??这样的话会不会影响到系统的性能?
      

  8.   

    @@error只针对当前连接的,如同@@identity一样,不同客户端(连接)的@@error是互不干扰的,毫无关系.