October 15, 2007 at 1:04 am
Hi all,
Is there any option to declare variables dynamically?
R
October 15, 2007 at 2:34 am
Could you describe in more detail what you mean by declaring variables dynamically? You can declare a variable at any time. If you create them on demand, how would reference them.
But something that may solve your problem (whatever it is), are table variables. You can create a table variable that stores generic name value pairs like (this is the nearest I can think of dynamic variables):
declare @variables table (name varchar(10), val sql_variant)
insert into @variables values('variable1', cast(10 as money)) -- an example name value pair
If you know the types of the variables you want to create, you may specify those in the table instead of sql_variant (which I would personally avoid)
Out of curiosity, what are you trying to do?
Andras
October 16, 2007 at 11:32 am
The only way I can think of is to use dynamic sql, but there may be a better way. Below is a sample.
declare @var table
(
var_name varchar(20),
var_datatype varchar(20)
)
insert into @var values ('@test','int')
declare @name as varchar(20)
declare @type as varchar(20)
set @name = (select var_name from @var)
set @type = (select var_datatype from @var)
exec(' declare ' + @name + ' ' + @type + '
set ' + @name + ' = ' + ' 100' +
' select ' + @name)
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply