x

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, 2010 at 04:38 PM in Default

avatar image

OnlyGraphite
41 6 6 10

(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, 2010 at 05:58 PM

avatar image

Matt Whitfield ♦♦
29.5k 62 66 88

(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

SQL Server Central

Need long-form SQL discussion? SQLserverCentral.com is the place.

Topics:

x56

asked: Mar 24, 2010 at 04:38 PM

Seen: 20927 times

Last Updated: Oct 03, 2012 at 05:02 PM

Copyright 2016 Redgate Software. Privacy Policy