2010-03-02 80 views
5

有没有办法将@my_variable字符串转换为值为@my_variablet-sql从变量名字符串获得变量值

我有一个存储变量名称的表。我需要得到这个变量的值。事情是这样的:

DECLARE @second_variable AS NVARCHAR(20); 
DECLARE @first_variable AS NVARCHAR(20); 
SET @first_variable = '20'; 
SET @second_variable = SELECT '@first_variable'; --here I want that @second variable be assigned a value of "20". 

回答

1

最有可能的解决你的问题是要解决/改变/修复的设计,需要你为什么会have a table which stores names of variables

0

尝试sp_executesql的

declare @f nvarchar(20) 
declare @s nvarchar(20) 
declare @sT nvarchar(100) 

set @f = '20' 
set @sT = 'set @s = ''' + @f + '''' 

exec sp_executesql @sT, N'@s nvarchar(20) output', @s output 

print @s 
+0

我不认为这是什么马库斯想要:他想把''@ f''(注意引号)转换为20,字符串“@ f''源于表格。在你的例子中,你显式使用'@ f',即它在编译时绑定。 – Heinzi 2010-03-02 14:29:28

1

您可以使用sp_executesql执行字符串(这样你就可以做类似sp_executesql 'SET @second_variable = ' + @name_of_variable;)。但是,将该语句放入sp_executesql中将不起作用,因为strings executed with sp_executesql or EXECUTE have their own variable scope,因此无法访问@second_variable和@first_variable。

所以,你可以做什么是移动你的完整代码(不含该变量的名称)为sp_executesql声明(未经测试):

DECLARE @name_of_variable NVARCHAR(MAX) 
SET @name_of_variable = ... 

EXECUTE sp_executesql N'...lots of code... ' + @name_of_variable + ' ...lots of code...' 
+0

http://www.sommarskog.se/dynamic_sql.html – 2010-03-02 14:03:32