I have two tables. TableOne
which contains two columns (name & value). TableTwo
can contain N no. of columns
. Number of rows in TableOne
will be equal to number of columns in TableTwo
.
see the below image for more information.
What I want:
When I run select query on TableTwo
, the result-set should pick the column names based on value
column of TableOne
. We need to match column name of TableTwo
with rows available in TableOne
and perform transform.
So the output should look like this:
ColumnOne | ColumnTwo | columnThree | ColumnFour
1 1 1 2015-05-08 15:28:22.630
2 2 2 2015-05-07 15:28:22.630
................
................
You can use dynamic sql to generate the query to execute based on the values in the first table. Here is an example:
Declare @dynamicSQL nvarchar(200)
SET @dynamicSQL = 'SELECT ' + (SELECT stuff((select ',' + name + ' AS ' + value from Table1 for xml path('')),1,1,'')) + ' FROM Table2'
EXECUTE sp_executesql @dynamicSQL
SQL Fiddle: http://sqlfiddle.com/#!6/768f9/10
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments