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开发者_JAVA技巧_UserID
END
I tried using return but it didn't work
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
Just use the return statement:
RAISERROR('Error message', 16, 1)
RETURN
RAISERROR will throw an exception to the nearest catch block. 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
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.
精彩评论