SQL - INSERT data if no row in table

Hi Experts,

I have a stored proc that works. However, I believe it could be better structured. Basically, the sproc checks
 - if there is record in table1 insert records from table2 by using a SELECT statement, without a condition

- if there are record(s) in the table1, insert records from table2 by using a SELECT statement with a WHERE condition.

Simplified example code I wrote below:

DECLARE @maxDate datetime;
SELECT @maxDate = MAX(LastUpdated) FROM table1

IF NOT EXISTS(SELECT * FROM table1)
  INSERT INTO dbo.table1 ( TransactSourceID , Description, LastUpdated)
    SELECT  TransactSourceID , Description, LastUpdated
          FROM table 2
ELSE
  INSERT INTO dbo.table1 ( TransactSourceID , Description, LastUpdated)
    SELECT  TransactSourceID , Description, LastUpdated
      FROM table2 t2
    WHERE t2.LastUpdated > @maxDate

In reality, I have about 45 columns in both INSERT and SELECT column list, so it really looks hairy.

Please review and offer a better way to write this, hopefully without having to call the 45+ columns in each condiotion check. Thanks!!


 
godwineffiongAsked:
Who is Participating?
 
Guy Hengel [angelIII / a3]Billing EngineerCommented:

DECLARE @maxDate datetime;
SELECT @maxDate = MAX(LastUpdated) FROM table1

  INSERT INTO dbo.table1 ( TransactSourceID , Description, LastUpdated)
    SELECT  TransactSourceID , Description, LastUpdated
      FROM table2 t2
    WHERE t2.LastUpdated > @maxDate
           OR @maxDate IS NULL
       
0
 
godwineffiongAuthor Commented:
Impressive! Beautiful Code !!

It works
Thanks
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.