I am working on a dynamic SQL query for a MsSQL stored procedure.
There is a table search.ProfileFields
that contains the actual column names in a table I need to query.
My goal is to have the SQL select the specific column in the table, dynamically from its parent query..
A little confusing, heres an example:
DECLARE @sql nvarchar(max)
SELECT @sql = '
SELECT
pfs.SectionID,
pfs.SectionName,
pfs.Link,
(
SELECT
pf.FieldID,
pf.FieldTitle,
pf.FieldSQL,
pf.Restricted,
pf.Optional,
(
SELECT
pf.FieldSQL
FROM
Resources.emp.EmployeeComplete as e
WHERE
e.QID = @QID
) as Value
FROM
search.ProfileFields as pf
WHERE
pf.SectionID = pfs.SectionID
ORDER BY
pf.[Order]
FOR XML PATH (''field''), ELEMENTS, TYPE, ROOT (''fields'')
)
FROM
search.ProfileFieldSections as pfs
WHERE
pfs.Status = 1
FOR XML PATH (''data''), ELEMENTS, TYPE, ROOT (''root'')'
PRINT @sql
EXECUTE sp_executesql @sql, N'@QID varchar(10)', @QID = @QID
In the inner most select
. I am querying pf.FieldSQL
. I am looking for the actual value that was received by the parent select
.
search.ProfileFields
has a column called FieldSQL
with a few results such as Name
, Age
, Location
.
That is what I am trying to get my inner most select
to do.
SELECT Name FROM ...
- Name in this case comes from the value of pf.FieldSQL
.
How can I go about querying a dynamic column name in this situation?