【问题标题】:How do I execute different SELECT statements based on a CASE如何根据 CASE 执行不同的 SELECT 语句
【发布时间】:2011-03-10 23:19:10
【问题描述】:

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

【问题讨论】:

    标签: sql sybase 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
    

    问题是您在嵌套的“选择”语句中缺少左括号和右括号:)

    【讨论】:

    • 您可能希望将第二个 then 子句中的左括号向右移动一个单词。
    • 仍然有语法错误,因为在第三行 then 在括号内
    【解决方案2】:

    只需在 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
    

    【讨论】:

      【解决方案3】:

      请注意,这不是case STATEMENT,而是case EXPRESSION。通过将查询括在括号中,您将它们(在语法上)转换为值。

      这在原理上类似于子查询,例如 " select name from Doctor where Salary = (select max(salary) from Doctor)"

      【讨论】:

        【解决方案4】:
        select 
          case when 
              LEN('1948082100')=8 then 
                  (select 'HELLO' )
              when 
              LEN('194808210')=10 then 
                  (select 'GOODBYE')
          end
        

        将值更改为测试结果。

        【讨论】:

          猜你喜欢
          • 2020-04-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-10-19
          • 1970-01-01
          • 2023-04-07
          • 1970-01-01
          相关资源
          最近更新 更多