Insert into table using Where clause

CONTEXT

I am using SQL Server Express to track activities and activities. I have two tables (table1, table2). Table 1 contains the startTime IDs and keys, while Table2 contains the ID, startTime, and endTime.

Whenever an entry is made, the row is filled in Table 1 with all keys. These keys are then inserted into table 2.

PROBLEM

The problem I am facing is that I want it to know if an ID already exists in table2, and if so, update the row for that ID rather than create 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 your help! Sorts new for SQL, let me know if there is anything I can do to improve my question.

+3


source to share


1 answer


How about something like this?



IF EXISTS (SELECT ID FROM Table2)
   Update Table2
   SET Table2.CURRENT_TIMESTAMP = Table1.CURRENT_TIMESTAMP  --However you want to update
   FROM Table2 tab2
   JOIN Table1 tab1 on Table1.ID = Table2.PTID
ELSE
   INSERT INTO Table2(ID, startTime)
   SELECT ID, CURRENT_TIMESTAMP
   FROM Table1

      

+2


source







All Articles