--示例--参数 declare @js int,@x1 int,@x2 int,@x3 int,@x4 int,@x5 int select @js=2 ,@x1=1,@x2=2,@x3=3,@x4=4,@x5=5 --处理 declare @x int set @x=100declare @s nvarchar(1000),@re int set @s='set @re=@x+@x'+cast(@js as varchar) exec sp_executesql @s ,N'@re int out,@x int ,@x1 int,@x2 int,@x3 int,@x4 int,@x5 int' ,@re out,@x ,@x1,@x2,@x3,@x4,@x5 select 处理结果=@re/*--测试结果处理结果 ----------- 102(所影响的行数为 1 行) --*/
谢谢大家,但是我想大家理解的好像都不对 zjcxc(邹建)我看不懂你写的 本来这段程序用ifelse条件判断也行 if @js=1 begin @x1='abc' end else if @js=2 begin @x2='abc' end else if @js=3 begin @x3='abc' end else if @js=4 begin @x4='abc' end else begin @x5='abc' end 显然,这样写太复杂了,如果能动态决定x后面的数值,就能知道赋给那个变量了。
select @js=1,@x=0
if @js=1
select @x1=@x+@js
--......
print @x1
--......
CREATE TABLE #Array
(
[Index] INT,
Value int
)
例如:@js中存储的是3,把字符串“abc”赋给@x+@js,即@x3=“abc”
如果@js中存储的是5,把字符串“abc”赋给@x+@js,即@x5=“abc”就是动态的决定赋给那个变量
declare @js int,@x1 int,@x2 int,@x3 int,@x4 int,@x5 int
select @js=2
,@x1=1,@x2=2,@x3=3,@x4=4,@x5=5
--处理
declare @x int
set @x=100declare @s nvarchar(1000),@re int
set @s='set @re=@x+@x'+cast(@js as varchar)
exec sp_executesql @s
,N'@re int out,@x int
,@x1 int,@x2 int,@x3 int,@x4 int,@x5 int'
,@re out,@x
,@x1,@x2,@x3,@x4,@x5
select 处理结果=@re/*--测试结果处理结果
-----------
102(所影响的行数为 1 行)
--*/
zjcxc(邹建)我看不懂你写的
本来这段程序用ifelse条件判断也行
if @js=1
begin
@x1='abc'
end
else
if @js=2
begin
@x2='abc'
end
else
if @js=3
begin
@x3='abc'
end
else
if @js=4
begin
@x4='abc'
end
else
begin
@x5='abc'
end
显然,这样写太复杂了,如果能动态决定x后面的数值,就能知道赋给那个变量了。
继续请教
--示例--参数
declare @js int,@x1 varchar(10),@x2 varchar(10),@x3 varchar(10),@x4 varchar(10),@x5 varchar(10)
select @js=2--处理
declare @x varchar(10)
set @x='abc'declare @s nvarchar(1000)
set @s='set @x'+cast(@js as varchar)+'=@x'
exec sp_executesql @s
,N'@x1 varchar(10) out,@x2 varchar(10) out,@x3 varchar(10) out,@x4 varchar(10) out,@x5 varchar(10) out
,@x varchar(10)'
,@x1 out,@x2 out,@x3 out,@x4 out,@x5 out
,@x
select x1=@x1,x2=@x2,x3=@x3,x4=@x4,x5=@x5/*--测试结果x1 x2 x3 x4 x5
---------- ---------- ---------- ---------- ----------
NULL abc NULL NULL NULL(所影响的行数为 1 行)
--*/
when 1 then @x1相关处理
when 2 tehn @x2相关处理
when 3 tehn @x3相关处理
when 4 tehn @x4相关处理
when 5 tehn @x5相关处理
end
when 1 then @x1相关处理这样的语句中,只能是表达式之类,不有是赋值这类处理语句
问题已解决。但是我还是不大明白sp_executesql 的用法,研究ing
关于我写的问题,已尽量将问题剥离出来。只能和朋友交流中说清楚,并不是有意绕圈子。