July 11, 2005 at 2:15 am
Dear all,
In a SQL-Script I want to use the column name as a variable, but a do not know the correct syntax. Example:
Declare @var1 char(2)
Set @var1 = 'xy'
Select [@var1] from table_ab
Can anyone help? Many thanks
urs
July 11, 2005 at 2:35 am
Try this.
Declare @var1 char(2)
Set @var1 = 'xy'
EXEC('Select ' + @var1 + ' from table_ab')
July 11, 2005 at 3:04 am
The correct systax is:
Declare @var1 char(2)
Set @var1 = 'xy'
Select @var1 as Var1 from table_ab
July 11, 2005 at 2:43 pm
that is not the correct syntax; the dynamic SQL Jon posted is the correct solution.
your SQL would return 'xy' for every row in the table table_ab, where Jon's statement would return the Value stored in the column xy for the table table_ab.
ie: results:
Var1
------------------------------
xy
xy
xy
xy
...
(476 row(s) affected)
instead of
xy
------------------------------
149.65
337.24
959.33
...
(476 row(s) affected)
Lowell
July 12, 2005 at 7:03 am
Guys you forgot the most important question to ask :
Why do you want to use dynamic sql??
Did you ever read this?
Viewing 5 posts - 1 through 4 (of 4 total)
You must be logged in to reply to this topic. Login to reply