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
a dynamic sql version isn't that's hard to do.
CREATE PROCEDURE [dbo].[VariableTopSelect]
-- Add the parameters for the stored procedure here
@t int
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare @sql nvarchar(max)
if (@t=10)
begin
set @sql='select top (10) * from table'
end
else
begin
set @sql='select * from table'
end
exec sp_executesql @sql
END
with this sp, if they send 10 to the sp, it'll select the top 10, otherwise it'll select all.
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.