2010-07-02 17 views
3

我在使用CASE语句执行查询时遇到问题。 根据我的情况(例如长度),我想执行不同的SQL语句。如何根据CASE执行不同的SELECT语句

有问题的示例查询如下:

select case 
    when char_length('19480821') = 8 
     then select count(1) from Patient 
    when char_length('19480821')=10 
     then select count(1) from Doctor 
end 

例外:

[错误]脚本线:1-5 --------------- -----------
关键字'select'附近的语法不正确。
消息:156,等级:15,状态:2
服务器:sunsrv4z7,行:2

我不能够正确的语法。我得到char_length的字符串作为来自用户的输入。 如何根据特定条件激发查询? CASE是正确的选择吗?或者我必须使用任何其他的东西。

回答

1
select 
    case when char_length('19480821')=8 then (select count(1) from Patient) 
     when char_length('19480821')=10 then (select count(1) from Doctor) 
    end 

的问题是,你缺少开在你的嵌套“选择”语句右括号:)

+1

你可能要移动的左括号第二则条款中一个字是正确的。 – potatopeelings 2010-07-02 06:37:52

+1

仍然有语法错误,因为在第三行然后是括号内 – 2010-07-02 06:38:16

+0

谢谢,修正:0 – VoodooChild 2010-07-02 06:40:21

4

只要把开闭左右支架select语句解决你的问题

select 
    case when 
     char_length('19480821')=8 then 
      (select count(1) from Patient) 
     when 
     char_length('19480821')=10 then 
      (select count(1) from Doctor) 
     end 
+0

+1哈哈,打败你吧! – VoodooChild 2010-07-02 06:38:11

+0

是啊.................. – 2010-07-02 06:39:19

2

请注意,这不是一个case STATEMENT,它是一个表达式。通过将查询括在括号中,您可以将它们(语法)转换为值。

这在原则上是一个子查询类似,如 “从医生选择名称,其中工资=(选择最大(从医生的工资))”