如何轻松地将列添加到临时表?

时间:2016-03-21 13:42:03

标签: sql sql-server

我可以将任意数量和类型的列添加到临时表中,而无需先定义它们:

select into #temp from table;

但是如果我想稍后在我的脚本中向这个临时表中添加列,我唯一知道的方法是:

alter #temp add column int;
insert into #table (column) select column from table;

如果我想添加多个列,这有点麻烦。有没有办法将列添加到临时表而不先定义它们?

3 个答案:

答案 0 :(得分:4)

添加列后,我认为insert是合适的。 Update似乎更像是您想要的操作。

一种选择是创建一个新的临时表:

select t.*, 'value' as col
into #temp1
from #temp t;

但是,对于现有表,无法添加列并同时填充它 - 除了提供默认值。

但是,您可以在相同时添加多个列:

alter #temp add col1 int, col2 int, col3 int;

update #temp t
    set col1 = 1, col2 = 2, col3 = 3;

答案 1 :(得分:3)

几乎可以肯定你知道你最终需要多少列。在创建#temp表时,可以使用虚拟常量值创建额外的列(不存在于表/查询结果中)。

e.g。

select *, '' as AdditionalStringColumn into #temp from table1;

select *, 0 as AdditionalIntegerColumn into #temp from table1;

select *, 0.0 as AdditionalDecimalColumn into #temp from table1;

通过这种方式,您不需要处理与alter table等交易的混乱,并且会有更好的表现。

答案 2 :(得分:0)

这是我喜欢使用这种添加列并在之后进行更新的方式:

MPI_Test

如果我使用这种添加方式:

select *
into #tmp
            from openquery(PARADOX_SRV_TEST, 'select * from D:\WinMent\DATA\TESTP\Npart.DB ') p


            ALTER TABLE #tmp ADD District nvarchar(10), SimbolClasa nvarchar(100)

            Update t 
            set t.District = (Select District from Cities c where c.Id = t.Localit)
            from #tmp t

            Update t 
            set t.SimbolClasa = (Select ISNULL(Simbol,'ND') as Simbol from CustomersCategory c where c.Cod = t.Clasa)
            from #tmp t

            select *,  ISNULL(c.Simbol,'Nedefinit') as Simbol from #tmp t 
            LEFT JOIN CustomersCategory c on c.Cod = t.Clasa

有时我会收到此类错误:

select *, '' as AdditionalStringColumn into #temp from table1;
相关问题