光标永不停止

Tuc*_*thy 1 sql-server t-sql cursors

我似乎在这个光标中犯了一个错误,我似乎无法弄清楚我做错了什么。

我已经确认select拉回了 2 行。但是当我将它传递到游标中选择出现字符串时,我可以提取我需要的确切值。这两行看起来像下面这样......

|DATAIDONTWANT|...|DATAIDONTWANT|<|1|DATAIDONTWANT|<|2|DATAIDONTWANT|...|
|DATAIDONTWANT|...|DATAIDONTWANT|<|1|DATAIDONTWANT|<|2|DATAIDONTWANT|...|
Run Code Online (Sandbox Code Playgroud)

光标似乎抓住了第一行并不断循环,永远不会进入下一行或结束程序。

declare
    @clobstringP varchar(max),
    @clobstring  varchar(max);

declare SevenCursor cursor for 
    select [value] as ClobP
    from string_split(@clobstring, '>')
    where value like '%<|2|%';

open SevenCursor;
fetch next from SevenCursor into @clobstringP;

while @@FETCH_STATUS = 0
begin
    insert into [database].dbo.tablestuff ( ValueP ) 
    select file387
    from ( 
        select 
             RowId387 = row_number() over( order by ( select 1 ) )
            ,file387  = [value]
        from string_split(@clobstringP, '|')
    ) a
    where a.RowId387 = 6;

end;

close SevenCursor;
deallocate SevenCursor;
Run Code Online (Sandbox Code Playgroud)

有人可以指出我正确的方向吗?

Pet*_*ier 6

光标将无限循环,除非和直到@@fetchstatus = 0。为了达到该状态,您需要继续浏览数据集。为了做到这一点,你应该添加fetch next from SevenCursor into @clobstringP;到块的内部begin ... end以便游标有一些东西可以迭代。


在这个阶段进行一些社论并建议您尝试完全放弃光标可能是明智的。游标非常漂亮,但经常被误用;从您提供的伪代码来看,您似乎正在尝试修复X何时可以绕过Y.

我可能会建议采用整个结果集并将string_split其转换为合理的#temp_table. 当你在这个缓存的结果集进行任何必要的更新/删除和验证它是合适的,试了一个 insert into dbo.tablestuff ...成功或基于批量评估的规则失败。例如:

declare @pipe_delimited_rows table ( 
    my_row varchar(max)
);
insert @pipe_delimited_rows ( my_row ) 
values 
(N'|DATAIDONTWANT|...|DATAIDONTWANT|<|1|DATAIDONTWANT|<|2|DATAIDONTWANT|...|'),
(N'|DATAIDONTWANT|...|DATAIDONTWANT|<|1|DATAIDONTWANT|<|2|DATAIDONTWANT|...|');

drop table if exists #cache_results; 
create table #cache_results ( 
     id int identity not null primary key
    ,ClobP nvarchar(max)
); 

insert #cache_results ( ClobP )
select ss.[value] as ClobP
from @pipe_delimited_rows pdr
cross apply string_split(pdr.my_row, '>') ss -- delimiting appropriately here, of course
where ss.[value] like '%<|2|%';

/* perform business logic to validate interim results here */

insert into [database].dbo.tablestuff ( ValueP ) 
select ClobP
from #cache_results;
Run Code Online (Sandbox Code Playgroud)

免责声明