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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3163675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 06:45:24  来源:igfitidea点击:

How do I execute different SELECT statements based on a CASE

sqlsybasecase

提问by surbhit4u

I am facing a problem in executing queries with CASE statement. Based on my condition,(for eg. length), I want to execute different SQL statement.

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

Problematic sample query is as follows:

有问题的示例查询如下:

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

Exception:

例外:

[Error] Script lines: 1-5 --------------------------
Incorrect syntax near the keyword 'select'.
Msg: 156, Level: 15, State: 2
Server: sunsrv4z7, Line: 2

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

I am not able to correct the syntax. I am getting the string for char_length as input from the user. How can I fire queries based on certain condition? Is CASE the right choice ? Or do I have to use any other thing.

我无法更正语法。我从用户那里获取 char_length 的字符串作为输入。如何根据特定条件触发查询?CASE 是正确的选择吗?或者我必须使用任何其他东西。

回答by Pranay Rana

Just put opening and closing bracket around select statement resolve you problem

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

回答by Phlamingo

Please do note that it is not a case STATEMENT, it is a case EXPRESSION. By enclosing the queries in parentheses, you are converting them (syntactically) to values.

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

This is similar in principle to a subquery, such as " select name from Doctor where salary = (select max(salary) from Doctor)"

这在原理上类似于子查询,例如“ select name from Doctor wheresalary = (select max(salary) from Doctor)”

回答by VoodooChild

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

The problem is that you are missing opening and closing brackets in your nested 'Select' statements :)

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

回答by Terrence Harry Holmes

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

Change the values to test results.

将值更改为测试结果。