如何为sql server中的变量赋值 [英] How to assign value to a variable in sql server
本文介绍了如何为sql server中的变量赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Hi,
Declare @M201305 numeric(12,2)= 2000
Declare @Var1 Varchar(10),@mth varchar(6)
Set @mth='201305'
select @Var1= '@M'+@mth
select @Var1
@ var1我需要2000的值。
如何ge这个?
For @var1 I neeed the value of 2000.
How to get this?
推荐答案
啊,我看到你想要做什么,将变量名和值混合在一起。你可以使用动态sql(基本上是一个字符串连接)和一个OUT参数来做到这一点。
没有别的方法可以做到这一点!
Ah I see what you are trying to do, mix variable names and values together. You can do this using dynamic sql (basically a string concatenation) and an OUT parameter.
There is no other way of doing this!
我明白了,是的,你将使用临时表来保存变量的值。
我个人可以在其他地方做这个事情然后数据库但是如果你必须..
I see, yes you'll be using a temp table to do that and keep the values of the variables.
Personally i would propably do this thing somewhere else then the database but if you have to ..
Declare @Var1 Varchar(10), @mth varchar(6)
declare @MyValues table(
Variable nvarchar(8),
Value numeric(12,2))
insert into @MyValues(Variable, Value)
values('@M201304', 1000)
insert into @MyValues(Variable, Value)
values('@M201305', 2000)
Set @mth='201305'
select top 1 Value from @MyValues where Variable = ('@M'+@mth)
如果我说得对,你想把@ Var1设置为@ M201305的值使用字符串连接创建变量名时...
这在SQL中是不可能的,但仅适用于动态SQL ...
If I got you right you want to set @Var1 to the value of @M201305 while creating the variable name using string concatenation...
That is impossible in SQL, but only with dynamic SQL...
这篇关于如何为sql server中的变量赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文