sql query stored in a column. How to execute this?

Experts - I have a table called "RunQuery" which has ReportID nvarchar(max) and Formula nvarchar(Max)

The data for this table gets generated from another stored procedure which provides an output like this;

ReportID    Formula
123             Select Name as Customer, sum(val) as Sum_Val from Table1
123             Select Org as Customer, Sum(Val) as Sum_Val from Table1
123             Select Prod as Customer, Sum(met) as Sum_Val from Table1
& so on.

Here, ReportID will be same for all rows however the content in formula will vary. it will have same headers if run seperately.

I need to run these individual queries & store the data in a output table.

Insert into Table_Output (Customer, Sum_Val)

I need this like a loop. can you help please?
ManjuIT - Project ManagerAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ste5anSenior DeveloperCommented:

DECLARE @RunQuery TABLE ( ReportID INT, Formula VARCHAR(MAX) );

VALUES	( 123, 'SELECT Name AS Customer, SUM(val) AS Sum_Val FROM Table1' ),
	( 123, 'SELECT Org AS Customer, SUM(Val) AS Sum_Val FROM Table1' ),
	( 123, 'SELECT Prod AS Customer, SUM(met) AS Sum_Val FROM Table1' );


SELECT	@Query += CHAR(13) + CHAR(10) + 'UNION ALL ' + RQ.Formula
FROM	@RunQuery RQ
WHERE	RQ.ReportID = 123;

SET @Query = STUFF(@Query, 1, 12, '');
SET @Query = 'INSERT INTO Table_Output (Customer, Sum_Val) ' + CHAR(13) + CHAR(10) + @Query;

EXECUTE ( @Query );

Open in new window


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ManjuIT - Project ManagerAuthor Commented:
Perfect ;) Thanks alot Stephan
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.