x
login about faq Site discussion (meta-askssc)

Select Column name dynamically based on rows from another table

Hello Helper,

I am having trouble joining 2 tables.

Table Names: QUESTION ANSWER

QUESTION Table contains a column with column name as ANSWER_LOCATION and it is INT data type. This column contains number of rows with values (1, 2, 3, 4 ...) and these numbers are column names in ANSWER table.

Example:

select QUESTION.ANSWER_LOCATION from QUESTION where ID = 5

The output of this query will be 5 (scalar value) and I need to join value (5) with ANSWER table to select the COLUMN5.

Please let me know if I need to provide more information.

Thanks in anticipation.

Cheers, D

more ▼

asked Mar 24 '10 at 04:38 PM in Default

OnlyGraphite gravatar image

OnlyGraphite
41 6 6 7

(comments are locked)
10|1200 characters needed characters left

1 answer: sort voted first
DECLARE @AnswerLocation int, @SQL varchar(MAX)
SELECT @AnswerLocation = ANSWER_LOCATION from QUESTION where ID = 5
SET @SQL = 'SELECT COLUMN' + convert(varchar, @AnswerLocation) + ' FROM ANSWER'
EXEC (@SQL)

However, you should really consider re-designing this data set, such that you have the same value in the ANSWER table, then you can enforce referential integrity with foreign keys etc. It would be worth posting the DDL in a separate question titled something along the lines of 'how should I re-design these tables'.

more ▼

answered Mar 24 '10 at 05:58 PM

Matt Whitfield gravatar image

Matt Whitfield ♦♦
29.2k 56 63 87

+1 Good answer and excellent suggestion.

Mar 25 '10 at 12:01 AM Tom Staab

Thank you very Matt. Intially I thought I can use dynamic SQL. However some of my SQL friends scared me of saying Dynamic SQL might cause SQL Injections.

Just wanted to clarify one more question.... Can I integrate Dynamic SQL in UDF's? Because the final requirement is to create UDF's based the above 2 tables.

Once thank you very much for your suggestion. Much appreciated.

I am also posting a seperate question for redisgning this table.

Cheers, DV

Mar 26 '10 at 02:48 AM OnlyGraphite
(comments are locked)
10|1200 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments



Facebook logo Follow Ask SSC on Facebook
Find Ask SSC on Google+
linkedin logo Find us on LinkedIn

Topics:

x47

asked: Mar 24 '10 at 04:38 PM

Seen: 9551 times

Last Updated: Oct 03 '12 at 05:02 PM

Copyright © 2002-2012 Simple Talk Publishing. All Rights Reserved. If you have any queries, please contact the site administrators.
Ask SQL Server Central is a community service provided by Red Gate.