简体   繁体   中英

Checking if an id exist in another table

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.

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
IF @CusID IS NULL
    BEGIN    
    raiserror('The customer does not exist', 0, 1)
    RETURN 1
    END

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM