简体   繁体   English

如何检查从多个表中删除所有行的存储过程是否成功?

[英]How can I check whether a stored procedure that deletes all rows from multiple tables succeeded?

I want a stored procedure that does the equivalent of the following我想要一个存储过程,它相当于以下内容

CREATE PROCEDURE Reset
AS
BEGIN
   DELETE * FROM SomeTable; 
   DELETE * FROM SomeOtherTable;
END

and also returns some indicator of success or failure.并返回一些成功或失败的指标。 How would I do that?我该怎么做? Only way I can think of is pre-calculating the number of rows that should be affected, but that seems so shoddy.我能想到的唯一方法是预先计算应该受到影响的行数,但这似乎很粗制滥造。

The following will produce a success/failure indicator based on the question, 'did the table reset complete without failure?'.以下将根据问题“表重置完成而没有失败?”产生成功/失败指示符。 It's wrapped in a transaction so that both deletes happen or none happen, which keeps your data clean.它被包装在一个事务中,这样既可以删除也可以不删除,从而保持数据干净。

BEGIN TRY
    BEGIN TRANSACTION;
       DELETE FROM SomeTable; 
       DELETE FROM SomeOtherTable;
    COMMIT TRANSACTION;
    -- success indicator
    SELECT 1 AS Result
END TRY
BEGIN CATCH
    IF @@TRANCOUNT > 0
    ROLLBACK TRANSACTION;
    -- failure indicator
    SELECT 0 AS Result
END CATCH

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

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