简体   繁体   English

如何终止存储过程?

[英]How can I terminate a stored procedure?

    CREATE PROCEDURE [dbo].[DeleteUser] 
-- Add the parameters for the stored procedure here
@original_UserID nvarchar(64) = UserID,
@temp int =0

    AS
    BEGIN
SELECT @temp = COUNT(*) FROM dbo.Users WHERE ManagerID = @original_UserID
END

BEGIN
IF(@temp>0)

    RAISERROR ('This user is manager of other user',
           16, -- Severity.
           1 -- State.
           );
           //Error occurred / Terminate the stored procedure 
END

BEGIN
SELECT @temp = COUNT(*) FROM dbo.Project WHERE ProjectManagerID = @original_UserID
END

I tried using return but it didn't work我尝试使用 return 但它没有用

P/S: I use this stored procedure in a girdview, which is contained in an updatePanel, I dont know this can cause problem or not P/S:我在一个 girdview 中使用这个存储过程,它包含在一个 updatePanel 中,我不知道这会不会导致问题

Just use the return statement:只需使用 return 语句:

RAISERROR('Error message', 16, 1)
RETURN

Another option is to use error trapping:另一种选择是使用错误捕获:

BEGIN TRY
<your current code>
END TRY

BEGIN CATCH
    IF @@TRANCOUNT > 0 ROLLBACK

    SELECT  @ErrMsg = ERROR_MESSAGE(),
            @ErrSeverity = ERROR_SEVERITY()

    SET @Msg = 'Error in Procedure XYZ!' 
    RAISERROR(@Msg, 0, 1) WITH NOWAIT

    RAISERROR(@ErrMsg, @ErrSeverity, 1)  WITH NOWAIT
END CATCH

You can alter the SEVERITY of the error in the last RAISERROR to force a terminating error as well.您可以更改最后一个RAISERROR中错误的SEVERITY以强制终止错误。

RAISERROR will throw an exception to the nearest catch block. RAISERROR 将向最近的 catch 块抛出异常。 So adding exception handling to your code will give the desired effect..因此,向您的代码添加异常处理将产生预期的效果..

BEGIN TRY

  BEGIN
    SELECT @temp = COUNT(*) FROM dbo.Users WHERE ManagerID = @original_UserID
  END

  BEGIN
   IF(@temp>0)
     RAISERROR ('This user is manager of other user',
                16, -- Severity.
                1 -- State.
                );
                //Error occurred / jump to the catch block
  END

  BEGIN
    SELECT @temp = COUNT(*) FROM dbo.Project WHERE ProjectManagerID = @original_UserID
  END

END TRY
BEGIN CATCH
  ...
END CATCH

http://msdn.microsoft.com/en-us/library/ms178592(v=sql.90).aspx http://msdn.microsoft.com/en-us/library/ms178592(v=sql.90).aspx

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

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