如果一列为空,则选择其他列

时间:2019-02-18 06:46:26

标签: sql-server

如果B. [名称]具有值,那么请选择以下内容

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

如果B. [Name]为Null,它将选择以下内容

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

我该怎么办?

2 个答案:

答案 0 :(得分:4)

您可以检查是否创建变量并分配它们的值,如下所示。

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

答案 1 :(得分:2)

您无需付出额外的努力,只需在第二个查询中添加左联接,因为两个查询都返回相同的数据(除了多余的列)。

您可以根据自己的条件(例如B.Name是否为空)根据需要使用结果。

示例:

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

我希望它会对您有所帮助:)