Sybase ASE SP正常处理外键约束违规

时间:2013-03-20 15:07:51

标签: stored-procedures sybase-ase

我正在尝试编写一个删除客户的Sybase ASE(15)存储过程。由于“外键约束违规”,DELETE可能会失败,在这种情况下,存储过程应该回滚事务并返回。

CREATE PROCEDURE dbo.spumb_deleteCustomer @customertodelete int AS BEGIN
   BEGIN TRANSACTION TRX_UMBDELCUSTOMER

   DELETE CREDITCARDS WHERE CUSTOMERID = @customertodelete
   DELETE CUSTOMER_SELECTION_MAP WHERE CUSTOMERID = @customertodelete
   DELETE CUSTOMERS WHERE ID = @customertodelete
   SELECT @rcnt = @@ROWCOUNT
   IF (@rcnt <> 1) BEGIN
     PRINT 'FAILED TO DELETE CUSTOMER'
     ROLLBACK TRANSACTION TRX_UMBDELCUSTOMER
     RETURN
   END 
   COMMIT TRANSACTION TRX_UMBDELCUSTOMER
END

在游标中运行此SP时,执行在第一个无效DELETE之后中止。如何使光标继续(或者更确切地说,SP不会引发错误)?

谢谢,西蒙

1 个答案:

答案 0 :(得分:0)

您应该检查@@ error!= 0以指示错误而不是查找@@ rowcount并处理这些错误,否则调用客户端可能会收到意外消息。如果检查@@ rowcount,则需要在每次删除后立即将其保存到变量中,因为每个命令都会重置它。

如果您特别想要获取外键违规消息,可以检查@@ error是否为546或547,因为这些将在失败时以@@错误返回:

http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc00729.1500/html/errMessageAdvRes/BABCCECF.htm

http://infocenter.sybase.com/help/index.jsp?topic=/com.sybase.infocenter.dc00729.1500/html/errMessageAdvRes/BABHJIEC.htm