SQL – Pass the result of the first query as the second query select column name

25 pts.
Tags:
Dynamic SQL
SELECT statement
SQL
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: March 24, 2009  11:07 AM
UPDATED: March 25, 2009  9:06 AM

Answer Wiki

Thanks. We'll let you know when a new response is added.

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:

<pre>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</pre>

Beware that dynamic SQL pose some security issues.

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

<a href=”http://www.sommarskog.se/dynamic_sql.html”>The Curse and Blessings of Dynamic SQL</a>

Discuss This Question: 2  Replies

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when members answer or reply to this question.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
  • Chris123
    I am using Microsoft SQL Server 9 on an SQL database
    25 pointsBadges:
    report
  • Chris123
    Thanks a lot Carlosdl works beautifully.
    25 pointsBadges:
    report

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

To follow this tag...

There was an error processing your information. Please try again later.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Thanks! We'll email you when relevant content is added and updated.

Following