SQL - Pass the result of the first query as the second query select column name
25 pts.
0
Q:
SQL - Pass the result of the first query as the second query select column name
I want to pass the result of a sql query as the column name in another query eg. (note there will be a single result for the first query)

SELECT
CASE
WHEN fld_type1 = 'A' THEN 'VAL_ALPHA1'
WHEN fld_type1 = 'D' THEN 'VAL_DATE1'
ELSE 'VAL_NUM1'
END AS FIELDNAME
FROM TABLE1

I want the result of the first query to pass to the second query as the select column name

SELECT <1st Query Result>
FROM TABLE2
WHERE ID = 8
ASKED: Mar 24 2009  11:07 AM GMT
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _
0
29805 pts.
0
A:
 RATE THIS ANSWER
+1
Click to Vote:
  •   1
  •  0
  • AddThis Social Bookmark Button
You will need dynamic SQL to achieve that.
What database are you using ? what version ?

In Sql Server, this would be one way to do it:

DECLARE @selectStmt nvarchar(4000),
@field nvarchar(100)
SELECT @field =
CASE
WHEN fld_type1 = 'A' THEN 'VAL_ALPHA1'
WHEN fld_type1 = 'D' THEN 'VAL_DATE1'
ELSE 'VAL_NUM1'
END
FROM table1
SET @selectStmt = 'SELECT '+@field+' FROM table2 WHERE id = 8'
EXEC(@selectStmt);
GO


Beware that dynamic SQL pose some security issues.

Have a look at the following article to read more about Dynamic SQL:

The Curse and Blessings of Dynamic SQL
Last Answered: Mar 25 2009  3:06 AM GMT by Carlosdl   29805 pts.
0
0
Discuss This Answer:
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _



_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

Chris123   25 pts.  |   Mar 25 2009  2:20AM GMT

I am using Microsoft SQL Server 9 on an SQL database

 

Chris123   25 pts.  |   Mar 25 2009  9:06AM GMT

Thanks a lot Carlosdl works beautifully.

 
0