如何基于CASE执行不同的SELECT语句 [英] How do I execute different SELECT statements based on a CASE

查看:155
本文介绍了如何基于CASE执行不同的SELECT语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

问题样本查询如下:

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行:

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

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

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.

推荐答案

只需在选择语句周围放置左括号和右括号即可解决您的问题

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

这篇关于如何基于CASE执行不同的SELECT语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆