select TOP (all)

前端 未结 8 2056
再見小時候
再見小時候 2020-12-15 16:46
declare @t int
set @t = 10
if (o = \'mmm\') set @t = -1
select top(@t) * from table

What if I want generally it resulted with 10 rows, but rarely a

8条回答
  •  鱼传尺愫
    2020-12-15 17:50

    The best solution I've found is to select the needed columns with all of your conditions into a temporary table, then do your conditional top:

    DECLARE @TempTable TABLE(cols...)
    
    INSERT INTO @TempTable
    SELECT blah FROM ...
    
    if (condition)
     SELECT TOP 10 * FROM @tempTable
    else
     SELECT * FROM @tempTable
    

    This way you follow DRY, get your conditional TOP, and are just as easy to read.

    Cheers.

提交回复
热议问题