Reputation: 217
I have a Customer table and an order table and i'm trying to check to make sure the customer in the order table exists in the customer table before i'm allowed to execute the rest of my script.
This is the code that's causing the problem,
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
When I try execute the script with a CustomerID that's not in the table it doesn't give me the error message. Any help would be appreciated.
Upvotes: 0
Views: 100
Reputation: 6463
IF @CusID IS NULL
BEGIN
raiserror('The customer does not exist', 0, 1)
RETURN 1
END
Upvotes: 0
Reputation: 69544
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
Since this procedure returns a value you will need to execute a little bit differently, something like
DECLARE @RtnValue INT;
EXECUTE @RtnValue = dbo.[Order] 44
SELECT @RtnValue; --<-- now you can use this value whatever you want to do with it
Upvotes: 2