John Roy
John Roy

Reputation: 67

Selecting other columns if one column is Null

If B.[Name] has value it well select the the following

Select 
    B.[Name],
    A.[Address], 
    A.TIN, 
    A.AuthorizedRep1Name, 
    A.AuthorizedRep1Email, 
    A.AuthorizedRep1Contact,
    A.AuthorizedRep2Name, 
    A.AuthorizedRep2Email, 
    A.AuthorizedRep2Contact, 
    A.RefundOfSecDep, 
    A.PayeeAddress,
    A.PayeeTIN
    From MembersTbl A
    join UserTbl B
    on A.UserID = B.ID

And if the B.[Name] is Null It will Select the following

Select 
    A.[Address], 
    A.TIN, 
    A.AuthorizedRep1Name, 
    A.AuthorizedRep1Email, 
    A.AuthorizedRep1Contact, 
    A.RefundOfSecDep, 
    A.PayeeAddress,
    A.PayeeTIN
    From MembersTbl A

What will I do?

Upvotes: 0

Views: 105

Answers (2)

AGH
AGH

Reputation: 353

You don't need to do extra effort just add left join in your second query as both query return same data except extra columns.

You can use result according to you requirement based on your condition like B.Name is null or not.

Example :

Select 
B.[Name],
A.[Address], 
A.TIN, 
A.AuthorizedRep1Name, 
A.AuthorizedRep1Email, 
A.AuthorizedRep1Contact,
A.AuthorizedRep2Name, 
A.AuthorizedRep2Email, 
A.AuthorizedRep2Contact, 
A.RefundOfSecDep, 
A.PayeeAddress,
A.PayeeTIN
From MembersTbl A
left join UserTbl B
on A.UserID = B.ID

I hope it will help you :)

Upvotes: 2

Suraj Kumar
Suraj Kumar

Reputation: 5643

You can check with creating a variable and assigning their values as shown below.

declare @name varchar(20)
set @name = (select name from YourTable b where ...)
Now to check
if(@name is not null)
begin
     ----Your first query.
end
else
begin
     ----Your second query
end

Upvotes: 4

Related Questions