如何在SQL2005中循环添加列

DECLARE @i int
set @i=0
WHILE @i<10
BEGIN
alter table test add lie+@i int
set @i=@i+1
END
就可以添加lie1,lie2,lie3,lie4……
@i是控制循环的次数,也可以理解为要添加的列数

************
补充:
************
1、建一个表,保存你要追加的字段名和字段类型
如:create table t_tmp(id int IDENTITY(1,1) not null,col_name varchar(100),col_type varchar(100));

2、把你想要动态追加的字段和类型全写入表中
如:
insert into t_tmp(col_name,col_type) values('t1','int');
insert into t_tmp(col_name,col_type) values('t2','date');
insert into t_tmp(col_name,col_type) values('t3','varchar(100)');
insert into t_tmp(col_name,col_type) values('t4','char(100)');

3、生成动态建表语句,并创建表
declare @str varchar(2000)
set @str='create table ttt('
select @str=@str + col_name+' '+col_type+',' from t_tmp
set @str=substring(@str,1,len(@str)-1)+')'
select @str
exec(@str)

------------------------------------------------------------------------------------------------------------

declare @min varchar(4),@max varchar(4), @sqlstr varchar(8000)
set @sqlstr = 'select FItemID'
select @min = min(years), @max = max(years) from #Happen3
while @min <= @max
begin
set @sqlstr = @sqlstr+',
sum(case when years = '+@min +' then(case when Months=1 then (FAmount / FQty)end)end) as Y'+@min +'P1Price,
sum(case when years = '+@min +' then(case when Months=2 then (FAmount / FQty)end)end) as Y'+@min +'P2Price,
sum(case when years = '+@min +' then(case when Months=3 then (FAmount / FQty)end)end) as Y'+@min +'P3Price,
sum(case when years = '+@min +' then(case when Months=4 then (FAmount / FQty)end)end) as Y'+@min +'P4Price,
sum(case when years = '+@min +' then(case when Months=5 then (FAmount / FQty)end)end) as Y'+@min +'P5Price,
sum(case when years = '+@min +' then(case when Months=6 then (FAmount / FQty)end)end) as Y'+@min +'P6Price,
sum(case when years = '+@min +' then(case when Months=7 then (FAmount / FQty)end)end) as Y'+@min +'P7Price,
sum(case when years = '+@min +' then(case when Months=8 then (FAmount / FQty)end)end) as Y'+@min +'P8Price,
sum(case when years = '+@min +' then(case when Months=9 then (FAmount / FQty)end)end) as Y'+@min +'P9Price,
sum(case when years = '+@min +' then(case when Months=10 then (FAmount / FQty)end)end) as Y'+@min +'P10Price,
sum(case when years = '+@min +' then(case when Months=11 then (FAmount / FQty)end)end) as Y'+@min +'P11Price,
sum(case when years = '+@min +' then(case when Months=12 then (FAmount / FQty)end)end) as Y'+@min +'P12Price'
set @min = @min+1
end
set @sqlstr = @sqlstr +' into ##Happen4 from #Happen3 where Not(FQty=0) group by FItemID'
exec(@sqlstr)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值