簡體   English   中英

SQL Server中基於第一個表列值的條件為null

[英]Condition in SQL server based on first table column value is null

我是SQL查詢的新手。

我有2個數據庫DB1和DB2。

DB1包含具有Name,Address和Code列的表A,DB2包含具有Name1,Address1列的表B。

如果代碼不為null,則我想從tableA中選擇Name,Address,否則name1&address1應該來自tableB。

請幫我。

  select top 1
  a.name 'MyName',
  a.address 'MyAddress'
  from DB1.table1 a
  where a.code <> null

假設您的tableA和TableB的主鍵為“名稱”

select 
case when a.Code is not null then a.Name else b.Name end as Name
,case when a.Code is not null then a.Address else b.Address end as Address
from DB1..tableA a
left join DB1..tableB b on a.Name=b.name

要么

select 
case when isnull(a.Code,'')<>'' then a.Name else b.Name end as Name
,case when isnull(a.Code,'')<>'' then a.Address else b.Address end as Address
from DB1..tableA a
left join DB1..tableB b on a.Name=b.name

如果表a和表b之間沒有關系,這也可能起作用。

select distinct(code),name, address from (
select 
case when t1.code IS NULL 
then t2.code else t1.code end as code, 
 case when t1.code IS NULL then t2.name else t1.name end as name, 
case when t1.code IS NULL then t2.address else
t1.address 
end address
from t1, t2) t;

小提琴

您可以用db1和db2中的表替換t1和t2。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM