sql如何使用游标查询指定行记录

sql使用游标可以查询第N条到第M条记录吗?怎么查?
2025-01-05 10:28:05
推荐回答(4个)
回答(1):

可以
不过不用游标也可以

select * from (select *,row_number() over(order by 排序列) as rownum from table) a
where rownum>=n and rownum<=m

回答(2):

--用游标
DECLARE @COLUMN1 VARCHAR(10)
DECLARE @LineNum INT
SET @LineNum = 1
DECLARE CUR_TEST CURSOR FOR
SELECT 语句

OPEN CUR_TEST

FETCH NEXT FROM CUR_TEST INTO @COLUMN1,...

WHILE @@FETCH_STATUS = 0
BEGIN
IF (@LineNum >= N and @LineNum <= M)
BEGIN
SELECT @COLUMN1,...
END
SET @LineNum = @LineNum + 1
END

CLOSE CUR_TEST
DEALLOCATE CUR_TEST

--用双TOP直接取出,从前M条倒序取出前(M-N)条,等同于取出了N到M之间的
SELECT TOP (M-N) * FROM (SELECT TOP M * FROM 表名 WHERE 语句 ORDER BY COLUMNname DESC)

回答(3):

SQL Server 游标这样用

DECLARE @N INT,@M INT
SELECT @N=5,@M=10
DECLARE Cur1 SCROLL CURSOR FOR
SELECT * FROM sysobjects
OPEN Cur1
FETCH ABSOLUTE 5 FROM Cur1
DECLARE @i INT
SET @i=1
WHILE @@FETCH_STATUS=0
BEGIN
SET @i=@i+1
IF @i<=@M-@N+1
FETCH NEXT FROM Cur1
ELSE
GOTO Roy
END
Roy:
CLOSE Cur1
DEALLOCATE Cur1

回答(4):

当然可以,但如果想查第N条到第M条记录会有很多比游标更方便快速的方法,具体的可Hi我谈谈