[英]How do I execute different SELECT statements based on a CASE
我在使用 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 是正確的選擇嗎? 或者我必須使用任何其他東西。
只需在 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
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 STATEMENT,而是一個 case EXPRESSION。 通過將查詢括在括號中,您將它們(在語法上)轉換為值。
這在原理上類似於子查詢,例如“ select name from Doctor wheresalary = (select max(salary) from Doctor)”
select
case when
LEN('1948082100')=8 then
(select 'HELLO' )
when
LEN('194808210')=10 then
(select 'GOODBYE')
end
將值更改為測試結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.