2

I want to update the table and I am not known which column is going to update. Here is the simple example

Update tablename
set 
if col1='A' then col1='IA',col2='XXX'
if col3='A' then col3='IA', col4='XXX'
where
(col1='A' and col2='UNKNOWN') or (col3='A' and col4='UNKNOWN')

Here either col1 or col3 surely contains 'A'

Please provide me correct query

2 Answers 2

5

Try this query

UPDATE tablename
SET col1=(CASE WHEN col1 LIKE 'A' THEN col1='IA' ELSE col1 END),
col2=(CASE WHEN col1 LIKE 'A' THEN col2='XXX' ELSE col2 END),
col3=(CASE WHEN col3 LIKE 'A' THEN col3='IA' ELSE col3 END),
col3=(CASE WEHN col3 LIKE 'A' THEN col4='XXX' ELSE col4 END)
WHERE
(col1='A' AND col2='UNKNOWN') OR (col3='A' AND col4='UNKNOWN')
Sign up to request clarification or add additional context in comments.

Comments

0

And old post, but for those Googlers who stumble upon this. This won't work. e.g.

THEN col1='IA'

will return a boolean and set col1 to 1 i.e. true Instead just return the 'IA' with THEN 'IA' ELSE col1 END

For clarity:

UPDATE tablename
SET col1=(CASE WHEN col1 LIKE 'A' THEN 'IA' ELSE col1 END),
col2=(CASE WHEN col1 LIKE 'A' THEN 'XXX' ELSE col2 END),
col3=(CASE WHEN col3 LIKE 'A' THEN 'IA' ELSE col3 END),
col3=(CASE WEHN col3 LIKE 'A' THEN 'XXX' ELSE col4 END)
WHERE
(col1='A' AND col2='UNKNOWN') OR (col3='A' AND col4='UNKNOWN')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.