title: Check if data exists (avoid duplication) in database before running some SQL Server code
body: <p>I'm working on automating the import of CSV data to a database. At this time I have code that results in a table called <code>#temp1</code> which looks like this:</p>
  
  <pre><code>CompetitionID   DateKickOff                TimeKickOff         TeamIDHome  TeamIDAway   ScoreHome   ScoreAway
  --------------- -------------------------- ------------------- ----------- ------------ ----------- ------------
  2               2013-03-08 00:00:00.000    14:02:00.0000000    21          43           0           4
  </code></pre>
  
  <p>At this point I need to check whether an identical combination of <code>DateKickOff</code> and <code>TeamIDHome</code> values exist in the database all ready, so as to avoid importing duplicate data. If this combination all ready exists on a row of table <code>Match</code> then I need to effectively skip the following code:</p>
  
  <pre><code>INSERT INTO Match
  SELECT *
  FROM #temp1
  
  --Add MatchID column to Temp Data file and fill it with the most recent match ID
  ALTER TABLE #CSVTest_Data
  ADD MatchID INT
  
  UPDATE #CSVTest_Data
  SET MatchID = (SELECT TOP 1 MatchID
                 FROM Match
                 ORDER BY MatchID DESC)
  
  INSERT INTO Data (MatchID,
                    OddsFirstTimeTaken, 
                    OddsLastTimeTaken, 
                    MarketName, 
                    Outcome, 
                    Odds, 
                    NumberOfBets, 
                    VolumeMatched, 
                    InPlay)
  SELECT MatchID,
         FirstTimeTaken, 
         LatestTimeTaken, 
         Market, 
         Outcome, 
         Odds, 
         NumberOfBets, 
         VolumeMatched, 
         InPlay
  FROM #CSVTest_Data
  </code></pre>
  
  <p>Obviously, if the data is not a duplicate entry then the code above needs to be run. I would really appreciate some help with this.</p>
  
  <p>EDIT: Just to clarify, the comparison of data needs to take place before the 'INSERT INTO Match' code occurs. If the data is not duplicate, SQL Server will increment the Primary Key of MatchID in the Match table. I then get this new MatchID value and write it to my second temporary table before writing to my 'Data' table. If no new entry was added to the 'Match' table, then no data must be written to the 'Data' table.</p>