Insert Into Table using Where Clause

Viewed 81

CONTEXT

I'm using SQL Server Express to track in and out actions. I have two tables (table1, table2). Table1 contains ID and startTime keys while Table2 contains ID, startTime, and endTime.

Whenever an entry is made, a row is populated in Table1 with all the keys. These keys are then inserted in to Table2.

PROBLEM

The problem I'm running in to is that I want it to recognize whether or not the ID already exists in Table2 - and, if it does, update the row for that ID instead of creating a new one.

CURRENT WORK

IF(COUNT(DISTINCT ID) > 1    --When ID has been seen more than once?
   INSERT INTO Table2(ID, startTime)
   SELECT ID, CURRENT_TIMESTAMP
   FROM Table1
   WHERE ID = Table2.PTID

ELSE
   INSERT INTO Table2(ID, startTime)
   SELECT ID, CURRENT_TIMESTAMP
   FROM Table1

Thanks in advance for any help! Sorta new to SQL, let me know if there's anything I can do to improve my question.

1 Answers
Related