循环语句是SQL中最常用的语句之一,接下来的SQL server内容就将以实例的方式示范SQL中循环语句的效果,供您参考,希望对您学习SQL中循环语句能够有所帮助。
假设HRS_Group存在7条记录,GroupID分别为3、4、5、6、7、13、14
执行如下Sql语句:
declare @sSql varchar(8000) select @sSql = '' select @sSql = @sSql + 'alter table #tt add A' + rtrim(convert(varchar(20), GroupID)) + ' decimal(5, 1) ' + CHAR(10) from HRS_Group where Type = 0 order by GroupID select @sSql
执行得到@sSql的值:
---------------------------------------------------------------------------------------- alter table #tt add A3 decimal(5, 1) alter table #tt add A4 decimal(5, 1) alter table #tt add A5 decimal(5, 1) alter table #tt add A6 decimal(5, 1) alter table #tt add A7 decimal(5, 1) alter table #tt add A13 decimal(5, 1) alter table #tt add A14 decimal(5, 1) ----------------------------------------------------------------------------------------
该Sql语句
select @sSql = @sSql + 'alter table #tt add A' + rtrim(convert(varchar(20), GroupID)) + ' decimal(5, 1) ' + CHAR(10) from HRS_Group where Type = 0 order by GroupID
是通过以GroupID大小为顺序,从数据库7次取值而对@sSq进行了7次拼接,起到了循环的效果,CHAR(10)表示换行
若将以上语句做如下修改:
declare @sSql varchar(8000) select @sSql = 'alter table #tt add A' + rtrim(convert(varchar(20), GroupID)) + ' decimal(5, 1) ' + CHAR(10) from HRS_Group where Type = 0 order by GroupID select @sSql
执行得到@sSql的值:
---------------------------------------------------------------------------------------- alter table #tt add A14 decimal(5, 1) ----------------------------------------------------------------------------------------
是通过以GroupID大小为顺序,从数据库7次取值而对@sSq进行了7赋值,但因为没有拼接,所以@sSql只保留了第7次的赋值