SQL 循環語句幾種寫法


1、正常循環語句

declare @orderNum varchar(255)
create table #ttableName(id int identity(1,1),Orders varchar(255))
declare @n int,@rows int
insert #ttableName(orders) select orderNum from pe_Orders where orderId<50
--select @rows=count(1) from pe_Orders
select @rows =@@rowcount 
set @n=1 
while @n<=@rows
begin
select @orderNum=OrderNum from PE_Orders where OrderNum=(select Orders from #ttableName where id=@n)
print (@OrderNum)
select @n=@n+1
end
drop table #ttableName

2、不帶事務的游標循環

declare @orderN varchar(50)  --臨時變量,用來保存游標值
declare y_curr cursor for   --申明游標 為orderNum
select orderNum from pe_Orders where orderId<50
open y_curr   --打開游標
fetch next from Y_curr into @orderN   ----開始循環游標變量
while(@@fetch_status=0)  ---返回被 FETCH 語句執行的最后游標的狀態,而不是任何當前被連接打開的游標的狀態。
begin
print (@orderN)
update pe_Orders set Functionary+@orderN where orderNum=@orderN   --操作數據庫
fetch next from y_curr into @orderN   --開始循環游標變量
end
close y_curr  --關閉游標
deallocate y_curr   --釋放游標

 

3、帶事務的游標循環

select orderNum,userName,MoneyTotal into #t from pe_Orders po
DECLARE @n int,@error int
--set @n=1
set @error=0
BEGIN TRAN   --申明 開始事務
declare @orderN varchar(50),@userN varchar(50)   --臨時變量,用來保存游標值
declare y_curr cursor for    --申明游標 為orderNum,userName
select orderNum,userName from PE_Orders where Orderid<50
open y_curr
fetch next from y_curr into @orderN,@userN
while @@fetch_status = 0
BEGIN
select isnull(sum(MoneyTotal),0),orderNum from #t where username=@userN
-- set @n=@n+1
set @error=@error+@@error  --記錄每次運行sql后 是否正確 0正確
fetch next from y_curr into @orderN,@userN
END
IF @error=0
BEGIN
commit tran   ---事務提交
END
ELSE
BEGIN
ROLLBACK TRAN   ---事務回滾
END
close y_curr
deallocate y_curr
DROP TABLE #t

 

4、if語句使用示例

declare @a int
set @a=12
if @a>100
begin
print @a
end
else
begin
print 'no'
end

 

5、while語句使用示例

declare @i int
set @i=1
while @i<30
begin
insert into test (userid) values(@i)
set @i=@i+1
end
-- 設置重復執行 SQL 語句或語句塊的條件。只要指定的條件為真,就重復執行語句。可以使用 BREAK 和 CONTINUE 關鍵字在循環內部控制 WHILE 循環中語句的執行。 本條為以前從網上查找獲取!


6、臨時表和try

 -- 增加臨時表
select * into #csj_temp from csj
-- 刪除臨時表 用到try
begin try -- 檢測代碼開始
drop table #csj_temp
end try
begin catch -- 錯誤開始
end catch


7、游標循環讀記錄

declare @temp_temp int
--declare @Cur_Name
--@Cur_Name="aaa"
--------------------------------- 創建游標 --Local(本地游標)
DECLARE aaa CURSOR for select House_Id from House_House where Deleted=0 or deleted is null
----------------------------------- 打開游標
Open aaa
----------------------------------- 遍歷和獲取游標
fetch next from aaa into @temp_temp
--print @temp_temp
while @@fetch_status=0
begin
--做你要做的事
select * from House_monthEnd where House_Id=@temp_temp
fetch next from aaa into @temp_temp -- 取值賦給變量
--
end
----------------------------------- 關閉游標
Close aaa
----------------------------------- 刪除游標
Deallocate aaa

 

 

創建時間:2019-11-27  更新時間:

 


免責聲明!

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



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