Pseudalitos
Pseudalitos

Reputation: 45

Update one column with two conditions

I want to do the following:

UPDATE table1 t1
SET column1 = 10 * t2.column1
FROM table2 t2
WHERE t1.column2 = 'yyy'

UPDATE table1 t1
SET column1 = 10 * t2.column2
FROM table2 t2
WHERE t1.column2 = 'zzz'

Is it possible to keep it in one semantic block?

Upvotes: 0

Views: 37

Answers (2)

ScaisEdge
ScaisEdge

Reputation: 133360

You could use CASE WHEN .. and apply the update only at the rows with valid condition ( 'yyy' OR 'zzz' )

    UPDATE table1 t1 
    SET    column1 = CASE 
            WHEN t1.column2 = 'yyy' THEN column1 = 10 * t2.column1 
            WHEN t1.column2 = 'zzz' THEN column1 = 10 * t2.column2 
    end
    FROM   table2 t2
    WHERE t1.column2  IN ( 'yyy','zzz')

Upvotes: 2

Eli
Eli

Reputation: 104

UPDATE table1 t1 
SET    column1 = ( 
       CASE 
              WHEN t1.column2 = 'yyy' THEN column1 = 10 * t2.column1 
              WHEN t1.column2 = 'zzz' THEN column1 = 10 * t2.column2 
       end) 
FROM   table2 t2

Upvotes: 1

Related Questions