sql语法求教

老七 2007-05-30 03:12:37
create table test (a int,数量01月 int,数量02月 int,数量03月 int,数量04月 int,数量05月 int,数量06月 int)
insert into test select 1,100,100,100,100,100,100
union select 1,200,200,200,200,200,200
union select 1,300,300,300,300,300,300
union select 1,400,400,400,400,400,400

Declare @I int
select @I=1
--select 数量+Right(100+@I,2)+月' from test --(语句一)
select [数量01月] from test --(语句二)
drop table test

问题:要求语句二对应@I
如果:select @I=5
结果对应为:select [数量02月] from test

...全文
146 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
-狙击手- 2007-05-30
  • 打赏
  • 举报
回复
create table test2 (a int,数量01月 int,数量02月 int,数量03月 int,数量04月 int,数量05月 int,数量06月 int)
insert into test2 select 1,100,100,100,100,100,100
union select 1,200,200,200,200,200,200
union select 1,300,300,300,300,300,300
union select 1,400,400,400,400,400,400

Declare @I int,@sql varchar(8000)
set @I=1
set @sql = 'select 数量'+ right('00'+cast(@I as varchar(2)),2) +'月 from test2'
exec(@sql) --(语句一)
--select [数量01月] from test2 --(语句二)


--问题:要求语句二对应@I
select @I=5
set @sql = 'select 数量'+ right('00'+cast(@I as varchar(2)),2) +'月 from test2'
exec(@sql) --(语句二)

drop table test2

/*
数量01月
-----------
100
200
300
400

数量05月
-----------
100
200
300
400

*/
老七 2007-05-30
  • 打赏
  • 举报
回复
谢谢:lwl0606(寒泉) 。
方法可行。
老七 2007-05-30
  • 打赏
  • 举报
回复
测试语句:
select case @I when 1 then 数量01月 when 2 then 数量02月 end from test
lwl0606 2007-05-30
  • 打赏
  • 举报
回复
Declare @I int
declare @sql nvarchar(4000)
select @I=1
set @sql='select 数量'+Right(100+@I,2)+'月 from test' --(语句一)
print @sql
exec(@sql)
老七 2007-05-30
  • 打赏
  • 举报
回复
请按上面要求把实际语句贴出来
zsforever 2007-05-30
  • 打赏
  • 举报
回复
那是你语法问题
老七 2007-05-30
  • 打赏
  • 举报
回复
笨点的办法 ,测试通不过!
zsforever 2007-05-30
  • 打赏
  • 举报
回复
--笨点的办法
case @I when 1 then 数量01月 when 2 then 数量02月 ..... end
--或者直接构造动态语句了

34,591

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧