SQL - Dynamic way to pass column names from a list

Viewed 881

I have a table where I store column namea which looks something like this :

header
Ref_1
Ref_4
Ref_6
Ref_100

I want to run a dynamic sql which will use the values above table as column names which should look like this :

select mycolumn1, mycolumn2 a from mytable1 b inner join a.ref = **b.ref_1**
select mycolumn1, mycolumn2 a from mytable1 b inner join a.ref = **b.ref_4**
select mycolumn1, mycolumn2 a from mytable1 b inner join a.ref = **b.ref_6**
select mycolumn1, mycolumn2 a from mytable1 b inner join a.ref = **b.ref_100**

here you see b.ref_{#} should be pass dynamically, is there any way I do this ?

I can do this easily using C# script or SQL Server Integration services, but I would like to do this in T_SQL ?

thanks in advance

2 Answers
Related