引导一个 Cursor 变量
LEAD over a Cursor variable
我试图在不移动光标的情况下获取下一条记录。即类似于 peek 函数的东西。这是我到目前为止编写的一些 sql 代码:
DECLARE
@Id varchar(80),
@Name varchar(80),
@NextId varchar(80)
BEGIN
SET @MyCursor = CURSOR FOR
SELECT id,name FROM dbo.My_TABLE
WHERE name like '%joe%';
OPEN @MyCursor
FETCH NEXT FROM @MyCursor
INTO @Id, @Name
WHILE @@FETCH_STATUS = 0
BEGIN
print 'Id is :: ' + cast(@Id as varchar(80)) + ' : ' + @Name
SELECT @NextId=id, LEAD (id,1) OVER (ORDER BY id) FROM @MyCursor;
print 'The next record is :: ' + @NextId
FETCH NEXT FROM @MyCursor
INTO @Id, @Name
END;
但是,我收到一条错误消息:
The variable '@MyCursor' is a cursor variable, but it is used in a place where a cursor variable is not valid.
当我发出 select 语句时,我可能会得到一些类似这样的数据
----+------
ID NAME
----+------
5 + Joes
6 + FakeJoe
7 + Joes
8 + Joes
9 + MikeJoes
对我来说,比较 ID 5 和 6 以查看名称是否匹配很重要。如果是这样,比如 7 和 8,我想删除后面的记录。如果没有,比如5和6,我想留下记录
游标变量不属于 FROM
。只需向查询本身添加一列:
SELECT id, name,
LEAD(id) OVER (ORDER BY id) as next_id
FROM dbo.My_TABLE
WHERE name like '%joe%';
我试图在不移动光标的情况下获取下一条记录。即类似于 peek 函数的东西。这是我到目前为止编写的一些 sql 代码:
DECLARE
@Id varchar(80),
@Name varchar(80),
@NextId varchar(80)
BEGIN
SET @MyCursor = CURSOR FOR
SELECT id,name FROM dbo.My_TABLE
WHERE name like '%joe%';
OPEN @MyCursor
FETCH NEXT FROM @MyCursor
INTO @Id, @Name
WHILE @@FETCH_STATUS = 0
BEGIN
print 'Id is :: ' + cast(@Id as varchar(80)) + ' : ' + @Name
SELECT @NextId=id, LEAD (id,1) OVER (ORDER BY id) FROM @MyCursor;
print 'The next record is :: ' + @NextId
FETCH NEXT FROM @MyCursor
INTO @Id, @Name
END;
但是,我收到一条错误消息:
The variable '@MyCursor' is a cursor variable, but it is used in a place where a cursor variable is not valid.
当我发出 select 语句时,我可能会得到一些类似这样的数据
----+------
ID NAME
----+------
5 + Joes
6 + FakeJoe
7 + Joes
8 + Joes
9 + MikeJoes
对我来说,比较 ID 5 和 6 以查看名称是否匹配很重要。如果是这样,比如 7 和 8,我想删除后面的记录。如果没有,比如5和6,我想留下记录
游标变量不属于 FROM
。只需向查询本身添加一列:
SELECT id, name,
LEAD(id) OVER (ORDER BY id) as next_id
FROM dbo.My_TABLE
WHERE name like '%joe%';