Sql server SQL Server合并查询-重复?

Sql server SQL Server合并查询-重复?,sql-server,merge,Sql Server,Merge,我有两个表变量 第一个表有1,3,5 第二个表有2,4,5 但是,当我运行以下查询时: DECLARE @t1 TABLE (a int) DECLARE @t2 TABLE (b int) INSERT INTO @t1 (a) VALUES ( 1 ),(3),(5) INSERT INTO @t2 (b) VALUES ( 2 ),(4),(5) ;WITH Source AS ( SELECT * from @t1 ) MERGE INTO @t2 U

我有两个表变量

  • 第一个表有
    1,3,5
  • 第二个表有
    2,4,5
但是,当我运行以下查询时:

 DECLARE @t1 TABLE (a int)
 DECLARE @t2 TABLE (b int)

 INSERT INTO @t1 (a) VALUES ( 1 ),(3),(5)  
 INSERT INTO @t2 (b) VALUES ( 2 ),(4),(5)

;WITH Source AS (
    SELECT * from  @t1
 )
 MERGE INTO @t2
 USING Source ON 1 = 0

 WHEN NOT MATCHED THEN
     INSERT (b) VALUES  (a);

 SELECT * FROM @t2 
我得到了未完全合并的结果:

我得到的不是
2,4,5,1,3
,而是
2,4,5,1,3,5

问题


为什么我看到一个双
5
?这是一个合并查询,5与第二个表中的其他5匹配。

因为您的
on
子句是
1=0
没有匹配项,所以插入所有行

on
子句更改为
a=b
将产生
2,4,5,1,3
的预期结果

a=b上的
测试仪:

在对源和目标使用别名时更加明确可能会有所帮助:

declare @t1 table (a int)
declare @t2 table (b int)
insert into @t1 (a) values ( 1 ),(3),(5)  
insert into @t2 (b) values ( 2 ),(4),(5)

;with source as (
  select * from  @t1
)
  merge into @t2 as target
  using source
    on source.a = target.b
    when not matched then
      insert (b) values  (a);

select * 
from @t2;

您正在匹配1=0,这将始终触发插入。您应该在Source.a=@t2.b上使用

1=0
?那总是错误的。您也不需要CTE,您可以使用@t2作为源编写
,例如:
在a=b上使用@t1作为源合并到@t2…