新聞中心
循環(huán)語句是SQL中最常用的語句之一,下面就將以實(shí)例的方式示范SQL中循環(huán)語句的效果,供您參考,希望對您學(xué)習(xí)SQL中循環(huán)語句能夠有所幫助。

讓客戶滿意是我們工作的目標(biāo),不斷超越客戶的期望值來自于我們對這個行業(yè)的熱愛。我們立志把好的技術(shù)通過有效、簡單的方式提供給客戶,將通過不懈努力成為客戶在信息化領(lǐng)域值得信任、有價值的長期合作伙伴,公司提供的服務(wù)項(xiàng)目有:主機(jī)域名、網(wǎng)絡(luò)空間、營銷軟件、網(wǎng)站建設(shè)、吳起網(wǎng)站維護(hù)、網(wǎng)站推廣。
假設(shè)HRS_Group存在7條記錄,GroupID分別為3、4、5、6、7、13、14
執(zhí)行如下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
執(zhí)行得到@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大小為順序,從數(shù)據(jù)庫7次取值而對@sSq進(jìn)行了7次拼接,起到了循環(huán)的效果,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
執(zhí)行得到@sSql的值:
- ----------------------------------------------------------------------------------------
- alter table #tt add A14 decimal(5, 1)
- ----------------------------------------------------------------------------------------
是通過以GroupID大小為順序,從數(shù)據(jù)庫7次取值而對@sSq進(jìn)行了7賦值,但因?yàn)闆]有拼接,所以@sSql只保留了第7次的賦值
網(wǎng)站欄目:SQL中循環(huán)語句的效果實(shí)例
URL鏈接:http://fisionsoft.com.cn/article/ccejeep.html


咨詢
建站咨詢
