插入表格不适用于选择左连接

时间:2016-01-27 09:45:48

标签: sql-server left-join

我正在尝试将openrowset查询中的新记录插入到表中不存在的现有表中。 这是代码:

insert into SRC_TABLE
REP.ID
,REP.COLUMN1
from openrowset (blabla) REP
left join SRC_TABLE TAB on REP.ID = TAB.ID
where TAB.ID is null

我收到错误:

Incorrect syntax near 'REP'.

但是当我按如下方式运行查询时:

select
REP.ID
,REP.COLUMN1
from openrowset (blabla) REP
left join SRC_TABLE TAB on REP.ID = TAB.ID
where TAB.ID is null

按预期工作,为我提供SRC_TABLE中不存在的行。 我做错了什么?

2 个答案:

答案 0 :(得分:2)

你几乎拥有它:

insert into table (ID, Column)
select
REP.ID
,REP.COLUMN1
from openrowset (blabla) REP
left join SRC_TABLE TAB on REP.ID = TAB.ID
where TAB.ID is null

答案 1 :(得分:1)

INSERT INTO dbo.table1 (...)
SELECT cte.DepartmentID
FROM OPENROWSET('SQLNCLI', 'Server=SQL_2012;Trusted_Connection=yes;',
    'SELECT DepartmentID FROM AdventureWorks2012.HumanResources.Department') cte
LEFT JOIN AdventureWorks2012.HumanResources.Department t ON cte.DepartmentID = t.DepartmentID