通过做一些研究,似乎不可能使用where子句进行插入? 我有一个表我想导入另一个表,其中特定的记录标准尚不存在。我该怎么做呢?
E.g伪代码 -
insert into table b (select * from table a) where not exists tableb.column1 = tablea.column1 and tableb.column2 = tablea.column2
这可能是通过加入来完成的吗?
答案 0 :(得分:2)
您可以使用INSERT INTO.. SELECT
NOT EXISTS
进行插入。
<强>查询强>
insert into [TableB]
select * from [TableA] as [t1] -- [TableA] and [TableB] structure should be same.
where not exists(
select 1 from [TableB] as [t2]
where [t1].[column1] = [t2].[column1]
and [t1].[column2] = [t2].[column2]
);
或者,如果表结构不相同且需要相同的几列,那么
<强>查询强>
insert into [TableB]([column1], [column2], ..., [columnN])
select [column1], [column2], ..., [columnN]
from [TableA] as [t1]
where not exists(
select 1 from [TableB] as [t2]
where [t1].[column1] = [t2].[column1]
and [t1].[column2] = [t2].[column2]
);
答案 1 :(得分:1)
您还可以将LEFT JOIN
与IS NULL
一起使用,如下所示:
INSERT INTO tableb
SELECT a.*
FROM tablea a
LEFT JOIN tableb b ON b.column1 = a.column1
AND b.column2 = a.column2
WHERE b.column1 IS NULL
答案 2 :(得分:1)
在SELECT部分中从INSERT语句引用表名将不起作用,因为INSERT本身不是查询,但是没有什么可以阻止在SELECT中查询目标表,从而生成要插入的数据集。
INSERT INTO tableb (column1, column2)
SELECT column1, column2 FROM tablea
WHERE NOT EXISTS (SELECT * FROM tableb
WHERE tableb.column1 = tablea.column1
AND tabled.column2 = tablea.column2)
答案 3 :(得分:1)
试试这个:
通过选择不存在的语句
进行插入Declare @table1 table(Id int , EmpName varchar(100) )
Declare @table2 table(Id int , EmpName varchar(100) )
Insert into @table1 values (1,'Ajay'), (2, 'Tarak') , (3,'Nirav')
Insert into @table2 values (1,'Ajay')
--Insert into table b (select * from table a) where not exists tableb.column1 = tablea.column1 and tabled.column2 = tablea.column2
INSERT INTO @table2 (id, empname)
select id, empname from @table1
EXCEPT
SELECT id, empname from @table2
Select * from @table1
Select * from @table2
通过合并
Insert into @table2 values (4,'Prakash')
Select * from @table1
Select * from @table2
Declare @Id int , @EmpName varchar(100)
;with data as (select @id as id, @empname as empname from @table1)
merge @table2 t
using data s
on s.id = t.id
and s.empname = t.empname
when not matched by target
then insert (id, empname) values (s.id, s.empname);
Select * from @table1
Select * from @table2