8

有没有办法从 sql server case/when 语句中的“then”运行 select 语句?(我需要从 then 语句运行子查询。)我不能在 where 语句中使用它。

select 
  case @Group 
    when 6500 then (select top 10 * from Table1)
    when 5450 then (select top 5 * from Table1)
    when 2010 then (select top 3 * from Table1)
    when 2000 then (select top 1 * from Table1)
    else 0 
  end as 'Report'
4

3 回答 3

2

一种选择是从查询中删除它并执行以下操作:

declare @Numrows int;
select @Numrows = (case @Group 
                        when 6500 then  10
                        when 5450 then 5
                        when 2010 then 3
                        when 2000 then 1
                        else 0
                   end);

select top(@NumRows) *
from Table1;

你也可以这样做:

with const as (
      select (case @Group 
                        when 6500 then  10
                        when 5450 then 5
                        when 2010 then 3
                        when 2000 then 1
                        else 0
                   end) as Numrows
    )
select t.*
from (select t.*, ROW_NUMBER() over () as seqnum
      from table1 t 
     ) t cross join
     const
where seqnum <= NumRows;

在这种情况下,您需要列出列以避免进入seqnum列表。

顺便说一句,通常在使用时top你也应该有order by. 否则,结果是不确定的。

于 2013-04-03T18:39:07.763 回答
2

SELECT 中不能有 SELECT。你可以使用 IF...ELSE 虽然例如

IF @Group = 6500
    select top 10* from Table1 AS Report
ELSE IF @Group = 5450
    select top 5* from Table1 AS Report
ELSE IF @Group = 2010
    select top 3* from Table1 AS Report
ELSE IF @Group = 2000
    select top 1* from Table1 AS Report
于 2013-04-03T18:42:04.143 回答
1

@Gordon 已经有了答案。这只是第二种选择。您可以使用动态查询。


declare @query varchar(max)
declare @Group int
set @query = ''

if @Group = 6500 
  set @query = 'select top 10 * from table1'
if @Group = 5450 
  set @query = 'select top 5 * from table1'
if @Group = 2010 
  set @query = 'select top 3 * from table1'
if @Group = 2000 
  set @query = 'select top 1 * from table1'

exec(@query)
于 2013-04-03T18:42:48.623 回答