我在存储过程中获取了一些参数。在对这些参数进行操作之前,我想验证它们,如果参数不符合要求,那么我想从存储过程中退出并显示错误消息。
示例代码:
create proc abcd
(
zip varchar(20),
name varchar(20),
network varchar(1)
)
-- validation section
IF (len(zip)<>5 OR LEN(zip)<>9)
begin
print "The zip must be of 5 or 9 characters"
<---- how to exit from here--->
end
IF (len(name)<2)
begin
print "The name must be of at least 2 characters"
<---- how to exit from here--->
end
---- main code
如上所述,如果出现错误,如何退出程序?
答案 0 :(得分:2)
您可以使用return
命令,如下所示
-- validation section
IF (len(zip)<>5 OR LEN(zip)<>9)
begin
print "The zip must be of 5 or 9 characters"
return 1
end
IF (len(name)<2)
begin
print "The name must be of at least 2 characters"
return 2
end
return 0 -- on the end of procedure
要捕获结果,您可以使用此代码:
declare @ProcResult int
execute @ProcResult = abcd @Zip = ..., @name...
select @ProcResult
答案 1 :(得分:1)
让我建议一些改变:
create procedure abcd
@zip varchar(20),
@name varchar(20),
@network varchar(1)
AS
-- validation section
IF (len(@zip)<>5 AND LEN(@zip)<>9)
begin
-- print "The zip must be of 5 or 9 characters"
raiserror 20000 "The zip must be of 5 or 9 characters"
return 1
end
IF (len(@name)<2)
begin
-- print "The name must be at least 2 characters"
raiserror 20001 "The name must be at least 2 characters"
return 2
end
raiserror
有很多选项,但这应该指向正确的方向。
编辑:添加了返回语句