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
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.