編輯 - 剛剛意識到你總是希望返回兩行,再工作......
更新代碼:
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)
解決它以什麼方式?表中最後一行後面的「下一行」應該是什麼? –
當currentId是最後一行時,下一行將是同一行。同時,我創建了只返回id的sp,所以如果它什麼都不返回,那麼我不執行從表中選擇字段的第二個過程。 – davor