根据CASE如何执行不同的SELECT语句

9

我在执行带有CASE语句的查询时遇到了问题。根据我的条件(例如长度),我想执行不同的SQL语句。

有问题的示例查询如下:

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是正确的选择吗?还是我必须使用其他东西。

4个回答

8
只需在选择语句的开头和结尾加上括号即可解决问题。
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

2
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

问题在于你的嵌套'Select'语句中缺少开头和结尾括号 :)

1
你可能想把第二个then子句中的开括号向右移动一个单词。 - potatopeelings
1
仍然存在语法错误,因为在第三行中,"then"被放在括号内。 - Pranay Rana

2
请注意这不是一个“case statement”,而是一个“case expression”。通过将查询语句括在括号中,您正在将它们(在语法上)转换为值。这与子查询的原理类似,例如“select name from Doctor where salary = (select max(salary) from Doctor)”。

-1
select 
  case when 
      LEN('1948082100')=8 then 
          (select 'HELLO' )
      when 
      LEN('194808210')=10 then 
          (select 'GOODBYE')
  end

将值更改为测试结果。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接