sql问题,大家帮忙
先看下面这个(有错误)
declare @i int
set @i=1
while (i<=(select max(igrade) from #aa))
begin
update #aa set 'g'+''+@i+''=ccode where igrade=''+@i+''
@i=@i+1
end
表中有g1,g2,g3.....字段
当@i=1时,我要修改g1的值,@i=2时,我要修改g2的值.....
大家帮我看看错在哪里
------解决方案--------------------不能这样用,可以把update语句拼成字符串,然后用exec执行,如
declare @sql varchar(1000)
set @sql='update aa set g'+cast(@i as varchar)+'=code where igrade='+cast(@i as varchar)
exec(@sql)
------解决方案--------------------declare @i int
declare @sql varchar(1000)
set @i=1
while (i <=(select max(igrade) from #aa))
begin
set @sql='update #aa set g'+ ltrim(@i)+'=ccode where igrade= '+ltrim(@i)
exec(@sql)
set @i=@i+1
end
------解决方案--------------------declare @i int
set @i=1
while (i <=(select max(igrade) from #aa))
begin
exec('update #aa set'+ 'g '+cast(@i as varchar(10))+'=ccode where igrade='''+'cast(@i as varchar(10)) ''' )
set @i=@i+1
end
------解决方案--------------------while 后面应该是@i<=
------解决方案--------------------看下面这个(有错误)
declare @i int
set @i=1
while (i <=(select max(igrade) from #aa))
begin
update #aa set 'g '+ ' '+@i+ ' '=ccode where igrade= ' '+@i+ ' '
@i=@i+1
end
表中有g1,g2,g3.....字段
当@i=1时,我要修改g1的值,@i=2时,我要修改g2的值.....
大家帮我看看错在哪里
------------------------
declare @i int
declare @j int
declare @sql as varchar(100)
set @i=1
select @j = max(igrade) from #aa
while @i <= @j
begin
set @sql = 'update #aa set g' + cast(@i as varchar) + '=ccode where igrade=' + cast(@i as varchar)
exec(@sql)
set @i = @i + 1
end
如果igrade是字符串型
set @sql = 'update #aa set g' + cast(@i as varchar) + '=ccode where igrade=''' + cast(@i as varchar) + '''
------解决方案--------------------青青,你都好久没来了吧.
------解决方案----------------------不好意思,少写了个as
declare @i as int
declare @j as int
declare @sql as varchar(100)
set @i=1
select @j = max(igrade) from #aa
while @i <= @j
begin
set @sql = 'update #aa set g ' + cast(@i as varchar) + '=ccode where igrade= ' + cast(@i as varchar)
exec(@sql)
set @i = @i + 1
end
如果igrade是字符串型
set @sql = 'update #aa set g ' + cast(@i as varchar) + '=ccode where igrade= ' ' ' + cast(@i as varchar) + ' ' '
------解决方案--------------------declare @i int,@maxi int,@sql varchar(8000)
select @i=1,@sql='',@maxi=max(igrade) from #aa
while (@i<=@maxi)
begin
set @sql=@sql+' update #aa set g'+rtrim(@i)+'=ccode where igrade='+rtrim(@i)
exec(@sql)
set @i=@i+1
end
------解决方案--------------------我都整天没事做,哎,混日子.