[英]Subquery with multiple columns within case statement
select case when integer=1 then (select col1,col2 from table1)
when integer=2 then (select col11,col22 from table2)
end
Can the subquery return multiple values,if not which approach is better option than this? 子查询可以返回多个值吗?如果没有哪个方法比这更好呢?
CASE
is for scalars not rows. CASE
用于标量而不是行。 For your problem I would use this: 对于您的问题,我将使用以下代码:
IF integer=1
SELECT col1 AS colA, col2 AS colB FROM table1
ELSE IF integer=2
SELECT col11 AS colA, col22 AS colB FROM table2
Maybe it's not particularly clean, but this should work: 也许它不是特别干净,但这应该可以工作:
SELECT CASE my_table.integer
WHEN 1 THEN table1.col1
ELSE table2.col11
END AS col_1,
CASE my_table.integer
WHEN 1 THEN table1.col2
ELSE table2.col2
END AS col_2
FROM my_table
LEFT OUTER JOIN table1
ON ....
LEFT OUTER JOIN table2
ON ....
...
Did you using MS Sql Server if yes you can try this 您是否使用过MS Sql Server,如果可以,可以尝试此操作
declare @script nvarchar(400)
select @script = case SomeField -- conditions field
when 1 then 'select * from [TableA]'
when 2 then 'select * from [TableB]'
end
from [TableC] where ...
exec sp_executesql @script
but be aware to concat any input from user to script. 但要注意将用户的所有输入连接到脚本。
You can do this with a single query using union all
: 您可以使用
union all
进行单个查询:
select col1, col2
from table1
where integer = 1
union all
select col1, col2
from table2
where integer = 2;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.