Dynamic SQL

Hi there,
I have a query that returns a set of columns name that I need to use for another SQL query.
This query returns those columns I need on my second query:
SELECT [SFIELDNAME]
  FROM [CUSTOMFIELD]
  where GCUSTOMFIELD in (SELECT  FKGCUSTOMFIELD FROM CUSTOMFIELDOBJECT where FKGCUSTOMFIELDLAYOUT='6f8dd820-1b29-48a1-8d80-219205de1208')
            and SFIELDNAME is not null
            and SFIELDNAME <> ''
            and SFIELDNAME in (select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'CUSTOMSAVERLICENSEMANAGEMENT')

Now for each row in that return set I need to add on my select on this query:

SELECT --Columns from above SFIELDNAME
 FROM CUSTOMSAVERLICENSEMANAGEMENT where ID='10d10f1a-b77f-495e-878b-1c5fe527f777'

How can I do this dynamically?
Thanks!
COHFLAsked:
Who is Participating?

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

x
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.

Vitor MontalvãoMSSQL Senior EngineerCommented:
Try this:
DECLARE @Cols VARCHAR(MAX)
DECLARE @MySelect VARCHAR(MAX)

SELECT @Cols = STUFF((SELECT ',' + [SFIELDNAME]
			FROM [CUSTOMFIELD]
			WHERE GCUSTOMFIELD in (SELECT  FKGCUSTOMFIELD FROM CUSTOMFIELDOBJECT where FKGCUSTOMFIELDLAYOUT='6f8dd820-1b29-48a1-8d80-219205de1208')
				and SFIELDNAME is not null 
				and SFIELDNAME <> ''
				and SFIELDNAME in (select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'CUSTOMSAVERLICENSEMANAGEMENT')
			FOR XML PATH('')), 1, 1, '' )

SET @MySelect = 'SELECT ' + @Cols + ' FROM CUSTOMSAVERLICENSEMANAGEMENT where ID=''10d10f1a-b77f-495e-878b-1c5fe527f777'''
EXECUTE(@MySelect)

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
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.