Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Cursor usage

Status
Not open for further replies.

jjlbmcnews

IS-IT--Management
Oct 4, 2001
60
0
0
GB
I'm using the following code in a cursor but I always seem to get one extra row at the end, which appears to be a duplicate of the last row of the table I'm working from. Can anybody point out why its doing this, code below.

DECLARE @vchTextFile varchar(255)
DECLARE @txSummary1 varchar(255)
DECLARE @iState1 varchar(255)
DECLARE @txSummary2 varchar(255)
DECLARE @iState2 varchar(255)
DECLARE @txSummary3 varchar(255)
DECLARE @iState3 varchar(255)
DECLARE @txSummary4 varchar(255)
DECLARE @iState4 varchar(255)
DECLARE @txHeadline varchar(255)
DECLARE @iHeadline varchar(255)

DECLARE SUMM_CURSOR CURSOR FOR
SELECT
.[vchTextFile],
.[txSummary1],
.[iState1],
.[txSummary2],
.[iState2],
.[txSummary3],
.[iState3],
.[txSummary4],
.[iState4],
.[txHeadline],
.[iHeadline]
FROM Summary AS S
OPEN SUMM_CURSOR
FETCH NEXT FROM SUMM_CURSOR
INTO @vchTextFile, @txSummary1, @iState1, @txSummary2, @iState2, @txSummary3,
@iState3, @txSummary4, @iState4, @txHeadline, @iHeadline
SELECT
@vchTextFile,
@txSummary1,
@iState1,
@txSummary2,
@iState2,
@txSummary3,
@iState3,
@txSummary4,
@iState4,
@txHeadline,
@iHeadline
WHILE @@FETCH_STATUS = 0
BEGIN
FETCH NEXT FROM SUMM_CURSOR
INTO @vchTextFile, @txSummary1, @iState1, @txSummary2, @iState2, @txSummary3,
@iState3, @txSummary4, @iState4, @txHeadline, @iHeadline
SELECT
@vchTextFile,
@txSummary1,
@iState1,
@txSummary2,
@iState2,
@txSummary3,
@iState3,
@txSummary4,
@iState4,
@txHeadline,
@iHeadline
END
CLOSE SUMM_CURSOR
DEALLOCATE SUMM_CURSOR
 
You don't need to do a separate "SELECT @vchTextFile,
@txSummary1 ....." The fetch will populate the variables.

BTW, there is always a way to solve the problem not using a cursor, it's usually much faster. I've had speed improvements of 2-3 orders of magnitude.
 
Ok, thanks very much for your reply, the problem I'm having though is that when I select the values from the variables and insert them into another table it always duplicates the last inserted entry, any ideas?
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top