【发布时间】:2014-02-23 22:05:20
【问题描述】:
架构和数据
我有两个具有以下架构和数据的表:
#table1:
create table #table1(
PK int IDENTITY(1,1) NOT NULL,
[TEXT] nvarchar(50) NOT NULL
);
PK TEXT
1 a
2 b
3 c
4 d
5 e
#table2:
create table #table2(
PK int IDENTITY(1,1) NOT NULL,
FK int NOT NULL,
[TEXT] nvarchar(50) NOT NULL
);
PK FK TEXT
1 2 B
2 3 C
问题
现在,如果我从 #table1 中选择所有并离开加入 #table2,如下所示:
select
#table1.PK,
(case #table2.[TEXT] when NULL then #table1.[TEXT] else #table2.[TEXT] end) as [TEXT]
from
#table1
left join
#table2 on #table2.FK = #table1.PK
;
输出如下:
PK TEXT
1 NULL
2 B
3 C
4 NULL
5 NULL
问题
我预计结果是:
PK TEXT
1 a <
2 B
3 C
4 d <
5 e <
那么为什么会发生这种情况(或者我做错了什么),我该如何解决这个问题?
源代码
if (OBJECT_ID('tempdb..#table1') is not null) drop table #table1;
if (OBJECT_ID('tempdb..#table2') is not null) drop table #table2;
create table #table1(PK int IDENTITY(1,1) NOT NULL, [TEXT] nvarchar(50) NOT NULL);
create table #table2(PK int IDENTITY(1,1) NOT NULL, FK int NOT NULL, [TEXT] nvarchar(50) NOT NULL);
insert into #table1 ([TEXT]) VALUES ('a'), ('b'), ('c'), ('d'), ('e');
insert into #table2 (FK, [TEXT]) VALUES (2, 'B'), (3, 'C');
select
#table1.PK,
(case #table2.[TEXT] when NULL then #table1.[TEXT] else #table2.[TEXT] end) as [TEXT]
from
#table1
left join
#table2 on #table2.FK = #table1.PK
;
drop table #table1;
drop table #table2;
【问题讨论】:
-
使用
CASE WHEN IS NULL--forgot IS。 -
@Mihai 感谢您的评论,但这会产生
incorrect syntax near the keyword 'IS'错误。
标签: sql sql-server-2008 select-case