成都网站建设设计

将想法与焦点和您一起共享

SQL中循环语句的效果实例

循环语句是SQL中最常用的语句之一,下面就将以实例的方式示范SQL中循环语句的效果,供您参考,希望对您学习SQL中循环语句能够有所帮助。

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:主机域名、网络空间、营销软件、网站建设、吴起网站维护、网站推广。

假设HRS_Group存在7条记录,GroupID分别为3、4、5、6、7、13、14

执行如下Sql语句:

 
 
 
  1. declare @sSql varchar(8000)
  2. select @sSql = ''
  3. select @sSql = @sSql + 'alter table #tt add A' + rtrim(convert(varchar(20), GroupID)) + ' decimal(5, 1) ' + CHAR(10)
  4.  from HRS_Group where Type = 0 order by GroupID
  5. select @sSql

执行得到@sSql的值:

 
 
 
  1. ----------------------------------------------------------------------------------------
  2. alter table #tt add A3 decimal(5, 1) 
  3. alter table #tt add A4 decimal(5, 1) 
  4. alter table #tt add A5 decimal(5, 1) 
  5. alter table #tt add A6 decimal(5, 1) 
  6. alter table #tt add A7 decimal(5, 1) 
  7. alter table #tt add A13 decimal(5, 1) 
  8. alter table #tt add A14 decimal(5, 1)
  9. ---------------------------------------------------------------------------------------- 

该Sql语句

 
 
 
  1. select @sSql = @sSql + 'alter table #tt add A' + rtrim(convert(varchar(20), GroupID)) + ' decimal(5, 1) ' + CHAR(10)
  2.  from HRS_Group where Type = 0 order by GroupID

是通过以GroupID大小为顺序,从数据库7次取值而对@sSq进行了7次拼接,起到了循环的效果,CHAR(10)表示换行

若将以上语句做如下修改:

 
 
 
  1. declare @sSql varchar(8000)
  2. select @sSql = 'alter table #tt add A' + rtrim(convert(varchar(20), GroupID)) + ' decimal(5, 1) ' + CHAR(10)
  3.  from HRS_Group where Type = 0 order by GroupID
  4. select @sSql

执行得到@sSql的值:

 
 
 
  1. ----------------------------------------------------------------------------------------
  2. alter table #tt add A14 decimal(5, 1) 
  3. ----------------------------------------------------------------------------------------

是通过以GroupID大小为顺序,从数据库7次取值而对@sSq进行了7赋值,但因为没有拼接,所以@sSql只保留了第7次的赋值


当前名称:SQL中循环语句的效果实例
转载来于:https://chengdu.cdxwcx.cn/article/ccejeep.html