sql中多層循環示例(有游標)


在需求處理中,我們會遇到需要通過SQL多層循環來處理的問題。如:A表中有8條數據,B表中有10條數據,需要實現A表中的每1條數據對應B表中的10條數據,最后就有了80條數據,從而實現一對多的關系。那如何通過循環來處理呢?
    下面就將為你介紹sql中while循環語句和通過游標來實現循環的實例,供你參考,希望對您學習SQL中的循環語句能夠有所幫助。
    :示例中A表相當於t_test1,B表相當於t_test2


一、WHILE循環實現
declare @user_tel varchar(20),@contact_tel varchar(20)
declare @i int,@j int,i_max int,@j_max int
select @i=1,@j=1
select @i_max=max(id) from t_test1
select @j_max=max(id) from t_test2

while @i<=@i_max
begin
 select @user_tel=user_tel from t_test1 where id=@i

 while @j<=@j_max
 begin
 select @contact_tel=user_tel from t_test2 where id=@j 
 insert into t_tmp(user_tel,contact_tel,nick_name,update_dt)
 select @user_tel,@contact_tel,'如夢',getdate()
 
 set @j=@j+1
 end
 set @j=1

set @i=@i+1
end

 


二、游標實現過程
--采用游標來實現循環處理
declare @user_tel varchar(20),@contact_tel varchar(20)
declare cur_test cursor for select user_tel from t_test1
declare @i int,@j_max int,
select @i=1
select @j_max=max(id) from t_test2
open  cur_test
fetch next from cur_test into @user_tel
while  @@fetch_status=0
begin
 
 while @i<=@j_max
 begin
 select @contact_tel=user_tel from t_test2 where id=@i 
 insert into t_tmp(user_tel,contact_tel,nick_name,update_dt)
 select @user_tel,@contact_tel,'如夢',getdate()
 
 set @i=@i+1
 end
 set @i=1

fetch next from cur_test into @user_tel


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM