SQL INSERT值(如果它们尚不存在)

时间:2013-12-18 13:25:32

标签: sql sql-server

我希望此查询将所有不同的网上商店日期插入到第二个表中,如果它们尚不存在于网上商店DataSet

以下查询似乎忽略了AND t1.[DataSet] = 'webshop'参数,并且未插入新的网上商店值,因为它们包含相同的日期范围,即。它们都包含01/02/2013

INSERT INTO [ImportedDateRange] ([DataSet],[DateRange]) 
select DISTINCT 'webshop', cast(T2.[OrderCreatedDate] as DATE) 
from webshop T2 
left join [ImportedDateRange] T1 
on cast(T2.[OrderCreatedDate] as DATE) = t1.[DateRange] 
where t1.[DateRange] is null
AND t1.[DataSet] = 'webshop'

理想的结果是,只有在网上商店尚不存在时才输入网上商店的日期范围(如果查询运行两次,这可以防止重复数据)

DataSet    DataRange
business   01/02/2013
business   02/02/2013
business   03/02/2013
webshop    01/02/2013
webshop    02/02/2013
webshop    03/02/2013

1 个答案:

答案 0 :(得分:3)

您应该将t1.[DataSet] = 'webshop'条件从WHERE类

移到JOIN
INSERT INTO [ImportedDateRange] ([DataSet],[DateRange]) 
select DISTINCT 'webshop', cast(T2.[OrderCreatedDate] as DATE) 
from webshop T2 
left join [ImportedDateRange] T1 
on cast(T2.[OrderCreatedDate] as DATE) = t1.[DateRange] 
         AND t1.[DataSet] = 'webshop'
where t1.[DateRange] is null