Seb
Seb

Reputation: 49

Update if exists but using Primary key

Trying to use following code for Update but facing an hudle how to get the ID from the select to use in an Update

any idea

My Code

    IF EXISTS (SELECT ID
               FROM   table1
               WHERE  ptid = 1 
                      AND ssfid = 5) 
      UPDATE table1 WITH (updlock) 
      SET    ssfid = 5 
      WHERE  ptid = 1; - trying to use ID frm the above Table - how could i?
else
      insert goes here 

Upvotes: 1

Views: 172

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520908

You could try using an updatable CTE:

WITH cte AS (
    SELECT ID, ssfid
    FROM table1
    WHERE ptid = 1 AND ssfid = 5
)

UPDATE cte
SET ssfid = 5;

The update logic does not make much sense, but this might be one way to execute what you described in your question.

Upvotes: 1

Related Questions