sqlexistsnorthwind

How can I check existence of 1 variable in 1 column in SQL?


I want to know if what user input parameter exists in a column in a table in SQL.

For example: check if "john" exists in column CustomerName in the Customer table.

I have tried exist keyword, but I do not completely understand it. Can someone help with a solution for this?

This is my code:

create procedure getOrderWithCusID
    @customerId char 
as 
    if (@customerId EXISTS(SELECT o.CustomerID FROM Orders o))
    begin
        select * 
        from Orders o 
        where o.CustomerID = @customerId;
    end
    else
        print('This customer does not exist');
    return;
end;

Solution

  • The procedure you're trying to write should look something like:

    create procedure getOrderWithCusID
    @customerId int 
    as 
    set nocount, xact_abort on;
    
    if exists (
      select * from Orders
      where CustomerId = @CustomerId
    )
    begin
      select <only necessary columns>
      from Orders 
      where CustomerID = @customerId;
    end;
    else
    begin
      print Concat('CustomerId ', @customerId, ' has no orders');
    end;
    

    Although really it's not necessary to use exists first and hit the table twice - you can simply check if any rows are returned and handle accordingly; also presumably your CustomerId is an int not a char with length 1...

    select <columns> from Orders where CustomerId = @CustomerId;
    
    if @@rowcount = 0
    begin
      <do this if customerId does not exist in table>
    end;