Friday, March 23, 2012

How can I avoid using a CURSOR inside of another CURSOR

I am trying to avoid using a CURSOR inside of another CURSOR.

Here's what I have to do...

I have 3 tables:

Table1 has 500,00 rows

Table2 has 25 rows

Table3 is empty

For each row in Table1, I want to INSERT 25 rows (from Table2) into Table3.

Using a CURSOR inside of another CURSOR, my code looks like this...

Define and open CURSORA for TABLE1

FETCH the first row from TABLE1 using CURSORA

WHILE (@.@.FETCH_STATUS<>-1)

Define and open CURSORB for Table2

FETCH the first row from Table2 using CURSORB

WHILE (@.@.FETCH_STATUS<>-1)

INSERT a row into TABLE3 (using the data from Table1 and Table2)

FETCH the next row from Table2 USING CURSORB

CLOSE the CURSORB cursor.

FETCH the next row from Table1 USING CURSORA

CLOSE the CURSORA cursor.

Using this CURSOR inside of another CURSOR is taking way too long.

Is there an SQL technique that I can use to get around using multiple cursors?

TIA!!!

DLdfrd

Use a setbased operation, its hard to guess the solution if you don′t give us more information what you actually want to do.

HTH, jens Suessmeyer.

|||You will probably want to use a Cross Join query -- TableA Cross Join TableB. Make a select statement that returns the columns you desire, then turn it into an Insert/Select.|||

Hey anomulous,

Thanks for the advice...

A Cross Join works very well. The join still takes awhile but one of the tables had 1.7 million rows but the Cross Join is a real big improvement.

This week, I have learned Inner Joins and Left Outer Joins. Today, I learned about Cross Joins.

Thanks again...

No comments:

Post a Comment