首页 > 解决方案 > SQL 仅选择单行号 x

问题描述

为了在 VBA 中处理 SQL 数据,我想使用从 SQL 数据库中逐行读取的循环(For...Next)。由于记录被删除,ID 列有间隙。例如,该表如下所示:

ID   Value
1    Peter
3    Paul
4    Mary
9    George

有四行我想跑

For i = 1 to 4
   SELECT ???
Next i

当然,“For each”也会有好处。

标签: sqlsql-servervbasql-order-bysql-limit

解决方案


如果您想要 4 行,请使用order byand top- 或 a fetch clause

select top(4) t.*
from mytable t
order by id

或者:

select t.*
from mytable t
order by id
offset 0 rows fetch first 4 rows only

然后,您可以遍历应用程序中的结果集。

另一方面,如果您只想要第 4 行,则只需更改fetch子句:

select t.*
from mytable t
order by id
offset 3 rows fetch next 1 row only

推荐阅读