How to select the nth row in a SQL database table?

后端 未结 30 3001
执笔经年
执笔经年 2020-11-22 06:06

I\'m interested in learning some (ideally) database agnostic ways of selecting the nth row from a database table. It would also be interesting to see how this can b

30条回答
  •  梦谈多话
    2020-11-22 06:41

    For SQL server, the following will return the first row from giving table.

    declare @rowNumber int = 1;
        select TOP(@rowNumber) * from [dbo].[someTable];
    EXCEPT
        select TOP(@rowNumber - 1) * from [dbo].[someTable];
    

    You can loop through the values with something like this:

    WHILE @constVar > 0
    BEGIN
        declare @rowNumber int = @consVar;
           select TOP(@rowNumber) * from [dbo].[someTable];
        EXCEPT
           select TOP(@rowNumber - 1) * from [dbo].[someTable];  
    
           SET @constVar = @constVar - 1;    
    END;
    

提交回复
热议问题