开发者

need to translate specific t-sql case in pl/sql

Can anyone tell me how to translate the following T-SQL statement:

SELECT fileld1 = CASE 
                   WHEN T.option1 THEN -1 
                   ELSE
                     CASE WHEN T.option2 THEN 0开发者_运维问答
                     ELSE 1
                   END
                 END
  FROM Table1 AS T

The point is I need to validate two different options from the table for a single field in the select statement..

I have tried to do somthing with an IF statement in pl/sql, but it just doesnt work for me:

SELECT IF T.option1 THEN -1 
       ELSE IF T.option2 THEN 0  
       ELSE 1 
       END 
  FROM Table1 AS T

I am not actually sure how to write IF statement inside the SELECT statement..

And also, I need to do it INSIDE the select statement because I am constructing a view.


Use:

SELECT CASE 
         WHEN T.option1 = ? THEN -1 
         WHEN T.option2 = ? THEN 0
         ELSE 1
       END AS field1
  FROM Table1 AS T

I can't get your original TSQL to work - I get:

Msg 4145, Level 15, State 1, Line 4 An expression of non-boolean type specified in a context where a condition is expected, near 'THEN'.

...because there's no value evaluation. If you're checking if the columns are null, you'll need to use:

SELECT CASE 
         WHEN T.option1 IS NULL THEN -1 
         WHEN T.option2 IS NULL THEN 0
         ELSE 1
       END AS field1
  FROM Table1 AS T

...or if you need when they are not null:

SELECT CASE 
         WHEN T.option1 IS NOT NULL THEN -1 
         WHEN T.option2 IS NOT NULL THEN 0
         ELSE 1
       END AS field1
  FROM Table1 AS T

CASE expressions shortcircuit - if the first WHEN matches, it returns the value & exits handling for that row - so the options afterwards aren't considered.


If I remember correctly, PL/SQL also supports the case. You just would have to move the column alias from "field1=" before the expression to "AS filed1" after the expression.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜