user1689283
user1689283

Reputation: 23

Using the names of columns stored within fields to retrieve data from a different table

I was wondering if there exists code to accomplish the following in SQL-Server 2008?

Table 1:

id    column name
-------------------
1     col1
2     col2
3     col3
4     col2

Table 2:

col1    col2    col3
--------------------
a       b       c

Result Table:

id    data
--------------------
1     a
2     b
3     c
4     b

Thanks in advance, I really have no idea how to do this.

Upvotes: 2

Views: 146

Answers (3)

Taryn
Taryn

Reputation: 247810

You can use UNPIVOT table2 to access the data from the columns:

select t1.id, t2.value
from table1 t1
left join 
(
  select value, col
  from table2
  unpivot
  (
    value
    for col in (col1, col2, col3)
  ) u
) t2
  on t1.name = t2.col

see SQL Fiddle with Demo

Or you can use a UNION ALL to access the data in table2:

select t1.id, t2.value
from table1 t1
left join 
(
  select col1 value, 'col1' col
  from table2
  union all
  select col2 value, 'col2' col
  from table2
  union all
  select col3 value, 'col3' col
  from table2
) t2
  on t1.name = t2.col

see SQL Fiddle with Demo

Upvotes: 2

Gordon Linoff
Gordon Linoff

Reputation: 1270401

You can do this with a case statement and cross join:

select t1.id,
       (case when t1.columnname = 'col1' then t2.col1
             when t1.columnname = 'col2' then t2.col2
             when t1.columnname = 'col3' then t2.col3
        end) as data
from table1 t1 cross join
     table2 t2

Upvotes: 0

RollRoll
RollRoll

Reputation: 8472

I dont see how you do it withou a column connection them:

Table1:
ID
ColumnName

Table2:
Table1ID
Letter


Select table1.id, table2.Letter 
from table1 
inner join table2 on table1.ID = table2.Table1ID

Upvotes: 0

Related Questions