基于第一个表列值的SQL Server中的条件为null

时间:2014-03-12 04:12:43

标签: sql sql-server

我是SQL Queries的新手..

我有2个数据库DB1& DB2。

DB1包含表A,其中包含Name,Address&代码栏& DB2包含表B,其中包含列Name1,Address1。

如果代码不为null,那么我想从表中选择名称,地址另外名称1& address1应该来自tableB。

请帮帮我。

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

2 个答案:

答案 0 :(得分:1)

假设您的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

OR

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

答案 1 :(得分:0)

这可能也有效,因为表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;

fiddle

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