1. 程式人生 > 實用技巧 >SQL 迴圈語句幾種寫法

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