如何根据CASE执行不同的SELECT语句
我在使用 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是正确的选择吗?或者我必须使用其他东西吗?
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只需将左括号和右括号放在 select 语句周围即可解决您的问题
Just put opening and closing bracket around select statement resolve you problem
问题是您在嵌套的“Select”语句中缺少左括号和右括号:)
The problem is that you are missing opening and closing brackets in your nested 'Select' statements :)
请注意,这不是一个 case 语句,而是一个 case EXPRESSION。通过将查询括在括号中,您可以将它们(从语法上)转换为值。
这在原理上类似于子查询,例如
“从医生中选择姓名,其中薪水=(从医生中选择最大(薪水))”
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)"
更改值以测试结果。
Change the values to test results.