然后,SQL,多个if语句,否则?

时间:2014-01-15 05:31:16

标签: sql

我是SQl的新手,并尝试自己学习。

我将学习SQL中if和else语句的用法

这是我尝试使用的数据,if或else语句 在下表中,我希望根据年龄使用sql查询更新注释,假设年龄在22到25之间,评论“在毕业生”

Age: 26 to 27, comments " post graduate"
Age: 28 to 30, comments "working and single"
Age: 31 to 33, comments " middle level manager and married"

表名:人

personid  lastname  firstname   age comments
1         Cardinal  Tom         22
2         prabhu    priya       33
3         bhandari  abhijeet    24
4         Harry     Bob         25
5         krishna   anand       29
6         hari      hara        31
7         ram       hara        27
8         kulkarni  manoj       35
9         joshi     santosh     28

4 个答案:

答案 0 :(得分:5)

How To Use Case

尝试使用CASE声明

Select personid,lastname,firstname,age,
       Case when age between 26 and 27 then 'post graduate'
            when age between 28 and 30 then 'working and single' 
            when age between 31 and 33 then ' middle level manager and married' 
            Else 'Nil'
       End comments 
from persons

答案 1 :(得分:1)

我可能会使用CASE语句

这样的东西
SELECT  *,
        CASE
            WHEN age BETWEEN 22 AND 25 
                THEN 'under graduate'
            WHEN age BETWEEN 26 AND 27
                THEN 'post graduate'
            WHEN age BETWEEN 28 AND 30 
                THEN 'working and single'
            WHEN age BETWEEN 31 AND 33
                THEN 'middle level manager and married'
            ELSE 'TADA'
        END Comment
FROM    persons

答案 2 :(得分:1)

根据您的要求,我们不能使用if ... else语句。案例......当陈述最合适时。另外一件事我们无法在任何查询中使用if ... else(我的意思是在select,insert,update中)。

和你的

Select personid,lastname,firstname,age,
   Case when age between 26 and 27 then 'post graduate'
   Case when age between 28 and 30 then 'working and single' 
   Case when age between 31 and 33 then ' middle level manager and married' 
   Else 'Nil'
   End comments 
from persons

答案 3 :(得分:0)

在标准SQL中,您将使用CASE语句。

update persons
set comments = case when age between 22 and 25 then 'undergraduate'
                    when age between 26 and 27 then 'post graduate'
               -- etc.
               end;