SQL Server 2012 -Union进入临时表

时间:2018-02-06 02:28:54

标签: sql sql-server

有2个表

Table:#Temp1 [1 row]
select ID from #Temp1
result: 1

Table:#Temp2 [1 row]
select ID from #Temp2
result: 1

select ID from #Temp1 
union 
select ID from #Temp2
result: 1

但是

select ID into #Temp3 from #Temp1 
union 
select ID from #Temp2
result: insert 2 rows

[为什么选择是一行,插入是两行?]

感谢。

2 个答案:

答案 0 :(得分:1)

您的声明不正确。

请参阅以下示例和SQL Server 2016 SP1的输出。

select 1 as id into #t1
select 1 as id into #t2

print ''
print 'select t1 union t2'
print '------------------'
select id from #t1
union
select id from #t2

print ''
print 'select into t3'
print '--------------'

select id into #t3 from #t1
union
select id from #t2

print ''
print 'select from t3'
print '--------------'
select id from #t3

drop table #t1
drop table #t2
drop table #t3

输出


(1 row(s) affected)

(1 row(s) affected)

select t1 union t2
------------------
id
-----------
1

(1 row(s) affected)


select into t3
--------------

(1 row(s) affected)

select from t3
--------------
id
-----------
1

(1 row(s) affected)

你会看到select into #t3受影响的是1行,而从表中选择也只返回1行。

您可能遇到的是union删除重复项的事实。因此,如果来自#t1#t2的两行具有相同的值,则union仅返回1行。但是,如果在不同的测试中,您具有不同的值,则将返回每个唯一的行。

请注意,union有一个可选的all限定符。所以,

select ...
union all
select ...

不会删除重复项。

答案 1 :(得分:0)

如果要插入联合,请尝试在联合

之后插入
Select Id into #temp3
From
(
Select ID from #Temp1 union select ID from #Temp2
)

这将允许在插入之前进行联合,这将允许来自表1和表2的id与联合一起产生单个记录,如果我同时存在

相关问题