Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
craigmacca
Posting Yak Master
142 Posts |
Posted - 2010-06-29 : 05:39:22
|
Hi i have a select statement which populates a temp tablefrom this temp table i need to loop through it and then insert 1. into customer table2. into details table (this has a customerId so i will need a @@identity)i am just not sure how to get the values out of the loop for the inserts?my code below is just a test to get it working, i will then be adding more fields. -- create the temp table Create Table #tempItemTable (memberNumber varchar(50), temp_id int identity(1,1)) -- first get a list of pro members that are new in max in hold them in a temp table insert into #tempItemTable select npo.CONTACTNO from Members npo left join Dir_Customers dc ON dc.MembershipNumber = npo.CONTACTNO where dc.MembershipNumber is not null -- new we have a list loop through and insert in to customers and business directory DECLARE @LoopId int DECLARE my_cursor CURSOR FOR SELECT memberNumber, surname, temp_id FROM #tempItemTable OPEN my_cursor FETCH NEXT FROM my_cursor INTO @LoopId WHILE @@FETCH_STATUS = 0 BEGIN declare @newId int INSERT INTO customer (memberNumber, surname) VALUES (@LoopId, ???) @newId = @@identity INSERT INTO details (customerId, surname) VALUES (@newId, ???) FETCH NEXT FROM my_cursor INTO @LoopId END CLOSE my_cursor DEALLOCATE my_cursor |
|
sql-programmers
Posting Yak Master
190 Posts |
Posted - 2010-06-30 : 05:44:42
|
Try the script,-- create the temp tableCreate Table #tempItemTable(memberNumber varchar(50), temp_id int identity(1,1),surname varchar(50))-- first get a list of pro members that are new in max in hold them in a temp tableinsert into #tempItemTableselect npo.CONTACTNO,nposurnamefrom Members npoleft join Dir_Customers dc ON dc.MembershipNumber = npo.CONTACTNOwhere dc.MembershipNumber is not null-- new we have a list loop through and insert in to customers and business directoryDECLARE @memberNumber varchar(50)DECLARE @surname varchar(50)DECLARE @newId intDECLARE my_cursor CURSOR FORSELECT memberNumber, surname FROM #tempItemTableOPEN my_cursorFETCH NEXT FROM my_cursorINTO @memberNumber,@surnameWHILE @@FETCH_STATUS = 0BEGININSERT INTO customer(memberNumber, surname)VALUES(@memberNumber, @surname)set @newId = @@identityINSERT INTO details(customerId, surname)VALUES(@newId, @surname)FETCH NEXT FROM my_cursorINTO @memberNumber,@surnameENDCLOSE my_cursorDEALLOCATE my_cursorSQL Server Programmers and Consultantshttp://www.sql-programmers.com/ |
 |
|
|
|
|
|
|