How do I execute different SELECT statements based on a CASE

心已入冬 提交于 2019-12-01 03:47:02

问题


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.

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

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.


回答1:


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

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

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




回答3:


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.

This is similar in principle to a subquery, such as " 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

Change the values to test results.



来源:https://stackoverflow.com/questions/3163675/how-do-i-execute-different-select-statements-based-on-a-case

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!