SELECT INTO with CASE语句

时间:2012-03-15 16:34:53

标签: sql-server sql-server-2008 tsql

有没有办法在select部分中执行带有CASE语句的SELECT INTO?我需要在进入新表之前进行一些数据转换。

3 个答案:

答案 0 :(得分:2)

是的,你可以:

SELECT CASE SourceField WHEN 1 THEN 'Yes' ELSE 'No' END AS SourceField
INTO DestinationTable
FROM SourceTable

答案 1 :(得分:1)

是。请务必为该列命名。还要确保将Case语句的值转换为显式类型以避免出现问题。

SELECT
    Cast((
        Case(ID)
            When (1) Then 'Text'
            Else NULL
        End) as varchar(50)
    ) as NewColumn
INTO #TempTable
FROM MyTable

答案 2 :(得分:1)

不确定。这里,#test被复制到#testnew,其中case语句在每个项目之前添加*,其值以'f'开头:

create table #test(id int, item1 varchar(10), item2 varchar(10))
insert into #test values(1,'foo','bar')
, (2,'fud','fudge')
go

select t.id
, item1=case when left(item1,1)='f' then '*'+item1 else item1 end
, item2=case when left(item2,1)='f' then '*'+item2 else item2 end
into #testnew
from #test t
go

select * from #testnew;
go

drop table #test;
drop table #testnew;
go

结果:

id          item1       item2
----------- ----------- -----------
1           *foo        bar
2           *fud        *fudge