当列为空时比较两列

时间:2013-09-09 20:50:47

标签: sql-server case

我遇到下一个查询的问题

select b.street_name 
from family a, address b,adress2 c 
where a.id_family=b.id_family 
  and a.id_famiy=c.id_family

我遇到的问题是,但有一些不合逻辑的原因,有2个表有地址,所以当b.street地址为''或null时,我想从地址比较另一个叫做cve_col的字段,这也是在address2上,其中包含街道的名称。

编辑:

我再次阅读它并且令人困惑,我需要像b.street_name =''那样c.cve_col = b.cve = col然后我可以在select select case when b.street_name='' then c.street_name end <上添加案例/ p>

2 个答案:

答案 0 :(得分:0)

我认为这应该有效:

select (case when b.street_name='' and b.street_name is null 
        then c.street_name end)street_name
from family a, address b,adress2 c 
where 
case when b.street_name<>'' and b.street_name is not null then a.id_family=b.id_family and a.id_famiy=c.id_family
else  c.cve_col=b.cve=col
end

答案 1 :(得分:-1)

关键是使用带有OR的case语句。看下面的脚本......它可以在测试数据库中重新运行。

drop table family
drop table [address]
drop table adress2
go

CREATE Table family (
    id_family int 
    , familyName varchar(50) NOT NULL
)

CREATE TABLE [address] (
    id_family int
    , street_name varchar(50)
    )

CREATE TABLE adress2  (
    id_family int
    , cve_col varchar(50)
    )
GO

INSERT family(id_family, familyName)
SELECT 1, 'Jones'
UNION SELECT 2, 'Smith'
UNION SELECT 3, 'Brown'

INSERT [address] (id_family, street_name)
SELECT 1, 'Jones St.'
UNION SELECT 2, ''
UNION SELECT 3, NULL

INSERT adress2(id_family, cve_col)
SELECT 1, ''
UNION SELECT 2, 'smith pl.'
UNION SELECT 3, 'brown ln.'

SELECT a.familyName
    , street_name = CASE WHEN b.street_name is NULL OR b.street_name = '' THEN C.cve_col
            ELSE b.street_name
        END
FROM family a 
    INNER JOIN [address] b ON A.id_family = b.id_family
    INNER JOIN [adress2] C ON A.id_family = C.id_family