TCMSSS
TCMSSS

Reputation: 147

One line IF condition in PL/SQL

It's possible to write one line if's in pl/sql? I'm just curious.

I want to write this snippet:

IF ( i.DECISAO_AT = 'S')
THEN 'PA'
ELSE 'I'
END IF;

And I want to know if it's possible to write it in one line, just like java. Like this:

IF ( i.DECISAO_AT = 'S') ? 'PA' : 'I' ;

Thanks!

Upvotes: 11

Views: 25981

Answers (5)

Gayan Dasanayake
Gayan Dasanayake

Reputation: 2021

You can use DECODE together with a SELECT INTO as below. "my_var" would be a variable declared to hold the decoded value.

SELECT DECODE(i.DECISAO_AT, 'S', 'PA', 'I') INTO my_var FROM DUAL;

Upvotes: 0

Sebz
Sebz

Reputation: 502

You could use the DECODE statement that you can use inline: The syntax for the DECODE function in Oracle/PLSQL is:

DECODE( expression , search , result [, search , result]... [, default] )

Upvotes: 3

Alex Poole
Alex Poole

Reputation: 191235

You can write an IF ... ELSE ... END IF; on one line as others have shown; but no, you cannot do what you suggested and write it "just like Java":

IF ( i.DECISAO_AT = 'S') ? 'PA' : 'I' ;

PL/SQL does not understand the Java ? and : syntax, and does not have its own ternary operators as such. You can only use what is described in the documentation. The closest thing to what I think you're asking, for this particular statement anyway, is probably a case:

CASE WHEN i.DECISAO_AT = 'S' THEN 'PA' ELSE 'I' END

Or maybe a decode, as xQbert already suggested in a comment. Neither is an "IF" any more though.

Upvotes: 16

Gary_W
Gary_W

Reputation: 10360

Sure you can, but down the road when you need to debug that if with several tests it will be a pain. Keep it on separate lines, thus easier to read, debug, comment and easier (and thus cheaper) for maintenance down the road. The next guy to work on it will thank you.

I read in a book (I think it was "C elements of style") once: "beware of clever, clever kills"). Keep it simple and easy. Code for the guy after you that has to maintain your code.

Upvotes: 1

Moudiz
Moudiz

Reputation: 7377

There is no problem in PL/SQL executing the code if it was in one line or several lines . What it matters the syntax is correct.

Upvotes: 3

Related Questions