我有一个查询,根据另一个数据库(database2)的结果将数据插入一个数据库(database1)。我担心的是,当我运行此查询时,我将引入一些潜在的重复项。
我的查询工作正常:
Insert into Customers (CustomerID, dateCreated)(
Select CustomerID, datecreated
FROM Database2.dbo.Customers
Where datecreated between @startdate and @enddate))
现在,我想通过检查CustomerID字段来捕获重复项,如果它已经存在于database1中,则不会插入到database1中。
我想到这样的事情:
Insert into Customers (CustomerID, dateCreated)(
Select CustomerID, datecreated
FROM Database2.dbo.Customers
Where datecreated between @startdate and @enddate))
Where not exists (Select customerid from customers)
我知道这不太对,但是我被卡住了。
答案 0 :(得分:4)
您可以使用左连接完成此操作。 检查联接表customerid值是否为null可确保它在源数据库中不存在。
INSERT into Database1.dbo.Customers
(CustomerID,
dateCreated)
SELECT
CustomerID,
datecreated
FROM Database2.dbo.Customers c2
LEFT JOIN Database1.dbo.Customers c1 ON c1.CustomerID = c2.CustomerID
WHERE c2.datecreated between @startdate and @enddate
AND c1.CustomerId IS NULL
答案 1 :(得分:0)
您可以使用if not exists,它只会扫描表格并查看它是否存在。请注意,它不会读取数据,因此无法进行检查。
IF NOT EXISTS (SELECT TOP 1 1 from Database1.dbo.customers WHERE customerid = 'the id you want to not duplicate')
BEGIN
Insert into Customers (CustomerID, dateCreated)(
Select CustomerID, datecreated
FROM Database.dbo.Customers
Where datecreated between @startdate and @enddate))
END