SQL中循环语句的效果实例


  本文标签: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次的赋值