Solved

loop through simple insert statement

Posted on 2009-07-15
1
220 Views
Last Modified: 2012-05-07
I have the following code - the below has to be executed 18 times - the column CPT has 18 occurances in it so rename it each execution and execute - is there a way - starting with CPT1 to execute the below through CPT18
INSERT INTO dbWorking2.dbo.[tblNCD_LAB]

SELECT     replace(ltrim(rtrim(CPT18)),',',''), ltrim(rtrim(ICD9)), effDate, termDate, resCode

FROM         dbo.NCD_Lab_090630

WHERE     (CPT18 IS NOT NULL) and isnumeric(ICD9) = 1

group by CPT18, ICD9, effDate, termDate, resCode order by CPT18, ICD9, effDate, termDate, resCode

Open in new window

0
Comment
Question by:tbaseflug
1 Comment
 
LVL 13

Accepted Solution

by:
TommyTupa earned 500 total points
Comment Utility
This is untested but you get the gist.  

Create a while loop and execute as dynamic SQL:


Declare @iCounter int
Declare @sCounter varchar(2)
Declare @SQL varchar(2000)

Set @iCounter = 1

While @iCounter <=18
BEGIN

Set @sCounter = cast(@iCounter as varchar(2))

Set @SQL = '
INSERT INTO dbWorking2.dbo.[tblNCD_LAB]
SELECT     replace(ltrim(rtrim(CPT18)),'','',''''), ltrim(rtrim(ICD9)), effDate, termDate, resCode
FROM         dbo.NCD_Lab_090630
WHERE     (CPT' + @sCounter + ' IS NOT NULL) and isnumeric(ICD9) = 1
group by CPT' + @sCounter + ', ICD9, effDate, termDate, resCode order by CPT' + @sCounter + ', ICD9, effDate, termDate, resCode
'
EXECUTE sp_executesql @SQL

--print @SQL

Set @iCounter = @iCounter +1

END
0

Featured Post

Comprehensive Backup Solutions for Microsoft

Acronis protects the complete Microsoft technology stack: Windows Server, Windows PC, laptop and Surface data; Microsoft business applications; Microsoft Hyper-V; Azure VMs; Microsoft Windows Server 2016; Microsoft Exchange 2016 and SQL Server 2016.

Join & Write a Comment

Suggested Solutions

Having an SQL database can be a big investment for a small company. Hardware, setup and of course, the price of software all add up to a big bill that some companies may not be able to absorb.  Luckily, there is a free version SQL Express, but does …
Slowly Changing Dimension Transformation component in data task flow is very useful for us to manage and control how data changes in SSIS.
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Via a live example combined with referencing Books Online, show some of the information that can be extracted from the Catalog Views in SQL Server.

772 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now