select TOP (all)

前端 未结 8 2053
再見小時候
再見小時候 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

    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.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题