mnlfischer
mnlfischer

Reputation: 397

SQL statement for loop through table and insert into another

I try to loop through a table and insert each row into antoher.

Statement:

SELECT firstname FROM importliste_3
OPEN rotate;
FETCH NEXT FROM rotate;
WHILE @@FETCH_STATUS = 0
   BEGIN
      --print firstname
      FETCH NEXT FROM rotate;
   END;
CLOSE rotate;
DEALLOCATE rotate;
GO

How can I access the firstname from the current selected row. I need a variable of the current firstname for an insert into different tables with primary and foreign keys.

I use the SQL Server 2008.

Upvotes: 0

Views: 2804

Answers (1)

D Stanley
D Stanley

Reputation: 152521

Before I insert something, I want to test it with a print.

Why? It's MUCH more efficient to just do it in one set operation:

INSERT INTO (destination)
SELECT (columns) from (sourcetable)

Turning that into a cursor simply to print each value for debugging purpose is a waste.

Upvotes: 1

Related Questions