如何终止存储过程?

时间:2011-08-11 13:53:35

标签: c# sql tsql sql-server-2008

    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

我尝试使用return但是没有用

P / S:我在girdview中使用这个存储过程,它包含在updatePanel中,我不知道这可能会导致问题

3 个答案:

答案 0 :(得分:3)

只需使用return语句:

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

答案 1 :(得分:1)

另一种选择是使用错误捕获:

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

您可以更改上一个SEVERITY中错误的RAISERROR以强制终止错误。

答案 2 :(得分:1)

RAISERROR会向最近的catch块抛出异常。因此,在代码中添加异常处理将产生预期的效果。

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