我有一个自动的过程,每周将数据附加到Table1
。它只有4列[Reason, Number of Occurences, Sent Date, and Program]
。 Table1
不断增长,不关心重复记录。 (每周只有26个记录,只有4列,所以表演/空间不是问题)SQL插入到不存在记录的位置
我有另一个表Table2
,我只想从Table1
区分记录。如果记录已经存在于Table 2
我不想插入记录。 我想下面的语句会的工作,但它并不:
begin transaction
insert into [Database]..[Table2]
select Distinct * from [Database]..[Table1]
where not exists (select * from [Database]..[Table2])
(0 row(s) affected)
如果我注释掉WHERE子句,它会工作,但它会插入已经在Table2
begin transaction
insert into [Database]..[Table2]
select Distinct * from [Database]..[Table1]
--where not exists (select * from [Database]..[Table2])
(83 row(s) affected)
存在的记录如何检查Table1
中的不同记录,并且如果该记录不存在于Table2
中,请插入该记录?
我使用MS SQL Server版本11.0.6020.0
IMO如果使用IF语句,你在做什么会更具有可读性。 – Seano666
你真的需要两张桌子 - 为什么不只是让table2成为table1的视图? – Hogan
@霍根,你知道什么...这实际上可能是一个选项。我会提出来的。 – MattR