0

I wanted to use if statement in Oracle update. Below is the condition that i wanted to achieve and i will not be able to use PL/SQL. I wanted to achieve the below result using update statement.

if code like'0001'  then
   code ='0001'
elsif code like'01' then 
   code = 'ok'
else 
   code = 'NOTOK'
end

I tried the below update statement not exactly what i need but just trying a simple update using case..

UPDATE tblname
SET CODE =  CASE
              WHEN CODE not like '01% OR CODE not like '0001% THEN
                'NOTOK'
            END
3
  • 1
    are you trying to update code or desc column ? OK logically should be desc Commented Nov 7, 2019 at 18:22
  • 1
    Well, Barbaros is right, that's quite confusing. In your pseudo code you have code, '001', 'ok', and 'NOTOK', and in your update statement there is DESC and 'DIRECT' instead. Commented Nov 7, 2019 at 18:26
  • 1
    Thanks Barbaros and Thorsten for looking into it, I have corrected it. Commented Nov 7, 2019 at 18:36

2 Answers 2

3

You can apply multiple WHEN ... THEN. The first match wins, so it works just like your if / else if.

UPDATE tblname 
SET code = CASE WHEN code LIKE '0001%' THEN '0001'
                WHEN code LIKE '01%' THEN 'ok'
                ELSE 'NOTOK'
           END;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Thorsten, I just found and i tried and it worked too. Thanks for your support.
0

Seems you want to use

UPDATE tblname 
   SET "DESC" = CASE 
                WHEN SUBSTR(CODE,1,2)='01' THEN 
                     'OK' 
                WHEN SUBSTR(CODE,1,4)='0001' THEN 
                     SUBSTR(CODE,1,4)
                ELSE
                     'NOT OK'
                END

desc is a reserved keyword. So, there cannot be a column name unquoted.

1 Comment

Thank you so much Barbaros. I was struggling to find the solution for 2 hours..

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.