使用sp选择上一行和下一行

时间:2011-11-23 17:12:54

标签: sql-server tsql

我想根据当前的id从表中选择上一行和下一行。我将当前的id发送到存储过程并使用此查询:

-- previous
select top 1 id from table where id < @currentId order by id desc
-- next
select top 1 id from table where id < @currentId order by id asc

问题是当我发送currentId时,它是表中的最后一个id并想要选择下一行。然后没有选择。当我发送currentId(表

中的第一个id)时,前一行的问题相同

是否可以在没有其他查询的情况下在sql中解决此问题?

2 个答案:

答案 0 :(得分:2)

您可以使用嵌套的top。您的“下一行”案例示例。

SELECT TOP 1 *
FROM   (SELECT TOP 2 *
        FROM   YourTable
        WHERE  id >= @currentId
        ORDER  BY id) T
ORDER  BY id DESC  

和“前一行”

SELECT TOP 1 *
FROM   (SELECT TOP 2 *
        FROM   YourTable
        WHERE  id <= @currentId
        ORDER  BY id DESC) T
ORDER  BY id ASC  

答案 1 :(得分:1)

编辑 - 刚才意识到你总是希望返回两行,重新开始......

更新的代码:

SELECT * FROM @t WHERE ID = (   select top 1 id 
                                from @t 
                                where id < 
                                    case 
                                        when exists (select id from @t where id < @ID) 
                                        then @ID 
                                        else (@ID + 1) 
                                    end 
                                order by id desc
                            )

UNION

SELECT * FROM @t WHERE ID = (   select top 1 id 
                                from @t 
                                where id > 
                                    case 
                                        when exists (select id from @t where id > @ID) 
                                        then @ID 
                                        else (@ID - 1) 
                                    end 
                                order by id
                            )

下面的原帖,在我意识到你想要什么之前

你真的很接近,你需要UNION运算符和一个小的语法更改你的查询。

SELECT * FROM [table] WHERE ID = (select top 1 id from @t where id < @ID order by id desc)
UNION
SELECT * FROM [table] WHERE ID = (select top 1 id from @t where id > @ID order by id)

当您传递的ID是第一行或最后一行时,这将返回1行,否则返回2行。

测试代码:

DECLARE @t TABLE
(
    Id int identity,
    Col varchar(200)
)

INSERT INTO @t VALUES('column one')
INSERT INTO @t VALUES('column two')
INSERT INTO @t VALUES('column three')
INSERT INTO @t VALUES('column four')
INSERT INTO @t VALUES('column five')

DELETE FROM @t WHERE ID = 3

DECLARE @Id int
SET @Id = 3 -- Change this to other values to further test

SELECT * FROM @t WHERE ID = (select top 1 id from @t where id < @ID order by id desc)
UNION
SELECT * FROM @t WHERE ID = (select top 1 id from @t where id > @ID order by id)