Solved

CURSOR and FETCH STATUS

Posted on 2003-12-09
2
3,333 Views
Last Modified: 2009-02-06
I have the following SQL Statement against MS SQL Server:
DECLARE @acct char(10)
SELECT @acct='418895'
DECLARE cur_comor CURSOR LOCAL SCROLL FOR SELECT TOP 10 [24] FROM tblComor WHERE PatAcctPA=@acct ORDER BY [24TeirStatus]
DECLARE @sql varchar(8000)
DECLARE @sql_val varchar(8000)
DECLARE @c char(10)
DECLARE @i as int
OPEN cur_comor
--print @@FETCH_STATUS
SELECT @i=1
SELECT @sql='insert into #piv_comor(PatacctPA'
SELECT @sql_val = 'VALUES(' + @acct
WHILE @@FETCH_STATUS=0
      BEGIN
      FETCH NEXT FROM cur_comor into @c
      --print 'HELLO: ' + @c
      SELECT @sql=@sql+',comor'+CONVERT(varchar(2),@i)
      SELECT @i=@i+1
      SELECT @sql_val=@sql_val+','''+@c +''''
      end
close cur_comor
--PRINT @sql + ') ' + @sql_val + ')'
DEALLOCATE cur_comor

If I run it once it is fine.  If I try to run it a second time I get a FetchStatus of -1.
Does anyone know what is going on and what I am doing wrong?
0
Comment
Question by:clangl
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
2 Comments
 
LVL 18

Accepted Solution

by:
ShogunWade earned 250 total points
ID: 9904614
Yes..

YOU have no FETCH NEXT FROM .....   before the WHILE @@FETCH_STATUS   loop
0
 
LVL 18

Expert Comment

by:ShogunWade
ID: 9904625
The idomatic was of cursoring is :


FETCH NEXT FROM ........
WHERE @@FETCH_STATUS=0
BEGIN
....
....
....
FETCH NEXT FROM..........
END
0

Featured Post

Does Your Cloud Backup Use Blockchain Technology?

Blockchain technology has already revolutionized finance thanks to Bitcoin. Now it's disrupting other areas, including the realm of data protection. Learn how blockchain is now being used to authenticate backup files and keep them safe from hackers.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
Viewers will learn how the fundamental information of how to create a table.
Viewers will learn how to use the SELECT statement in SQL to return specific rows and columns, with various degrees of sorting and limits in place.

626 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question