sql server - Why is my T-SQL cursor executing twice? -
sql-server code:
declare @offers varchar(100) declare @offers_seq varchar(100) declare result cursor select top 1 offers,offers_seq [rezjqwb01]..activebooking_offersdetails_seq open result while @@fetch_status=0 begin fetch next result @offers, @offers_seq declare @value varchar(100) = @offers while len(@value) >= 1 begin set @value = substring(@value,charindex(';',@value)+1,len(@value)) print @value end end close result deallocate result what i'm trying accomplish here split set of delimited values present in 1 cell , creating cursor complete column. first time run code gives below output:
2;6;7;8;9;12;13;14;17;19;21; 6;7;8;9;12;13;14;17;19;21; 7;8;9;12;13;14;17;19;21; 8;9;12;13;14;17;19;21; 9;12;13;14;17;19;21; 12;13;14;17;19;21; 13;14;17;19;21; 14;17;19;21; 17;19;21; 19;21; 21; 2;6;7;8;9;12;13;14;17;19;21; 6;7;8;9;12;13;14;17;19;21; 7;8;9;12;13;14;17;19;21; 8;9;12;13;14;17;19;21; 9;12;13;14;17;19;21; 12;13;14;17;19;21; 13;14;17;19;21; 14;17;19;21; 17;19;21; 19;21; 21; ideally should print once i'm not sure why loop runs twice. second time run this, gives output : 'command(s) completed successfully'.
kindly help. thanks.
the reason running twice aren't doing fetch until after you've checked @@fetch_status.
the steps this:
- check
@@fetch_status, zero, since nothing has been fetched. - fetch result
- run substring code
- check
@@fetch_statusagain, still zero, because record fetched in previous step - fetch result, fails cursor still pointing @ same row before
- run substring code again, same result
- check
@@fetch_statusagain, returns -1 because previous fetch failed.
for same reason 2 results running once, nothing second time, because @@fetch_status -1 previous execution. fix both issues, need fetch before checking status. you'll see 1 of following methods employed (psuedocode left exercise implement). typically use first option, find second easier read:
-- (declare , open cursor) while 1=1 begin fetch next cursor if @@fetch_status <> 0 break; -- (do stuff) end or
-- (declare , open cursor) fetch next cursor while @@fetch_status = 0 begin -- (do stuff) fetch next cursor end
Comments
Post a Comment