Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 324
  • Last Modified:

Binary query to see if a date exists in a table

I have to tables

table1 and table2

each of these tables has date1 and date2 respectively.

I have a process where I append the daily records from table2 to table1. I want to make sure they are not duplicated.

to do this I was thinking on checking and seeing that any of the dates in table2 exists in table 1

If any of the dates in table2.date2 exists in table1.date1

(Block select statement 1)
else
(block select statement2)

endif

I just need some help with the first if statement. How do I write the query so that it checks if any of the values in date2 exists in date1 giving me a true or false value.

thanks
0
damixa
Asked:
damixa
  • 2
1 Solution
 
Scott PletcherSenior DBACommented:
This code will INSERT only rows that don't already exist.

INSERT INTO dbo.table1 (
    date1, ...
    )
SELECT
    t2.date2, ...
FROM dbo.table2 t2
LEFT OUTER JOIN dbo.table1 t1 ON
    t1.date1 = t2.date2
WHERE
    t1.date1 IS NULL AND
    t1.date1 >= '...' AND
    t2.date2 >= '...'
0
 
Brian CroweCommented:
INSERT INTO table1 (date1)
SELECT t2.date2
FROM table2 AS t2
LEFT OUTER JOIN table1 AS t1
   ON t2.date2 = t1.date1
WHERE t1.date1 IS NULL

Obviously the column lists need to be adjusted to include any additional columns which you have not mentioned.
0
 
Scott PletcherSenior DBACommented:
Interesting ... I thought my earlier-posted answer was more complete.
0

Featured Post

NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now