[英]How to avoid CTE in query?
我准備了一個示例表,以展示我想要實現的目標。
drop table #Temp
create table #Temp
(
col1 nvarchar(50),
col2 nvarchar(50),
col3 nvarchar(50)
)
insert into #temp (col1,col2,col3) values (null, null, 'W')
如何避免這種 cte 並獲得相同的結果?
with cte as (
select COALESCE(col1,col2,col3) as result from #temp
)
select * from cte where result is not null
MS SQL 服務器 2017 架構設置:
create table Temp
(
col1 nvarchar(50),
col2 nvarchar(50),
col3 nvarchar(50)
)
insert into temp (col1,col2,col3) values (null, null, 'W')
insert into temp (col1,col2,col3) values (null, null, null)
insert into temp (col1,col2,col3) values ('A', 'B', 'W')
查詢 1 :
select * from temp
where COALESCE(col1,col2,col3) IS NOT NULL
查詢 2 :
select CASE WHEN COALESCE(col1,col2,col3) IS NULL THEN 'Undefined' ELSE
COALESCE(col1,col2,col3) END from temp
結果:
| col1 | col2 | col3 |
|--------|--------|------|
| (null) | (null) | W |
| A | B | W |
對於您的查詢,它相當於以下 2 個查詢
select COALESCE(col1,col2,col3) as result
from #Temp
where COALESCE(col1,col2,col3) is not null
或者
select *
from
(
select COALESCE(col1,col2,col3) as result from #Temp
) as D
where result is not null
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.