我有一个客户表和一个订单表,我试图检查以确保客户表中存在客户表中的客户,然后我才能执行其余的脚本。
这是造成问题的代码,
alter proc Order
@CustomerID int
as
Declare @CusID int
select @CusID = dbo.CustomerTable.CustomerID
from dbo.CustomerTable
inner join dbo.OrdersTable
on dbo.CustomerTable.CustomerID
= dbo.OrdersTable.CustomerID
where dbo.OrdersTable.CustomerID = @CustomerID
if(@CusID != @CustomerID)
begin
raiserror('The customer does not exist')
return 1
end
exec Order 44
当我尝试使用不在表中的CustomerID执行脚本时,它不会给我错误消息。任何帮助将不胜感激。
答案 0 :(得分:2)
ALTER PROCEDURE dbo.[Order] --<-- Avoid using key words for object names
@CustomerID int
AS
BEGIN
SET NOCOUNT ON;
IF NOT EXISTS
(select 1
from dbo.CustomerTable inner join dbo.OrdersTable
on dbo.CustomerTable.CustomerID = dbo.OrdersTable.CustomerID
where dbo.OrdersTable.CustomerID = @CustomerID)
BEGIN
RAISERROR('The customer does not exist', 16,1)
RETURN 1
END
RETURN @CustomerID;
END
EXECUTE PROC
由于此过程返回一个值,您需要执行一些不同的操作,例如
DECLARE @RtnValue INT;
EXECUTE @RtnValue = dbo.[Order] 44
SELECT @RtnValue; --<-- now you can use this value whatever you want to do with it
答案 1 :(得分:0)
IF @CusID IS NULL
BEGIN
raiserror('The customer does not exist', 0, 1)
RETURN 1
END