Link to home
Start Free TrialLog in
Avatar of Marcus Aurelius
Marcus AureliusFlag for United States of America

asked on

SQL Server how to use a VARIABLE to link tables in a SQL Script?

Experts

I'm dealing with the following issue:
I need to know how to use a VARIABLE as a linking-field in a SQL QUERY.

declare @variable1 varchar(30) = select top 1 fieldname1 from table_3

Note: Result of @variable1 is a string "Col1" and represents the name of a column in a table. This will be somewhat dynamic in that it can be different columns. (ie. Col1 or Col2 or Col5 etc..etc..)

I need to create a SQL script that will LINK on this @variable1

Like this:

select t1.col1, t1.col2, t2.col3, t2.col4
from table_1 t1
inner join table_2 t2 on t2.col1 = @variable1

The problem I'm having is that @variable1 is using the literal TEXT  "Col1" but I need it to actually be linking on the "DATA" within "Col1"...

Please advise on how to handle this issue?
ASKER CERTIFIED SOLUTION
Avatar of HainKurt
HainKurt
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Jeff Darling
Here is how to populate a variable from a query

 DECLARE @variable1 as varchar(30)

 select top 1 @variable1=fld1 from #mytable1

 print @variable1 

Open in new window

Avatar of Marcus Aurelius

ASKER

Thanks!