sql遊標的用法

遊標的寫法

參考代碼

USE [xxx]
GO
/****** Object:  StoredProcedure [dbo].[SDJS]    Script Date: 06/02/2020 09:39:11 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER proc [dbo].[SDJS]
as
begin
    DECLARE @rm_newid varchar(36);
    DECLARE @cust_guid varchar(36);
    DECLARE N_CUR_SDJS CURSOR FOR 
		select cust_guid from cust_info where sign=1
		OPEN N_CUR_SDJS
		FETCH NEXT FROM N_CUR_SDJS INTO @cust_guid
		WHILE @@FETCH_STATUS = 0
		BEGIN
           declare @use_price numeric(12,2);
           declare @billNo varchar(40);
           set @use_price=0;
           --查找除本期外所有未計算的設備費用
           select @use_price=isnull(sum(use_price),0) from change_db db
           left join device_info dev on dev.device_guid=db.device_guid
           left join rooms_man rm on rm.rm_newid = dev.cust_guid
           left join cust_info cus on cus.cust_guid = rm.cust_guid
           where (db.is_js is null or db.is_js=0)
           and end_time<=convert(varchar(10),getdate(),120)
           and cus.cust_guid=@cust_guid;
           --插入結算
           if @use_price>0
           begin
			   waitfor delay '00:00:00.100';
			   set @billNo = 'SD'+Replace(Replace(Replace(Replace(CONVERT(varchar(100), GETDATE(), 21),'-',''),' ',''),':',''),'.','')
               exec SDZD @cust_guid,@billNo;
			   insert into cust_charge (CHARGE_GUID,DEVICE_GUID,BILL_NO,BILL_DATE,PAY_TYPE,PAY_MONEY,PAY_STATE,OPER_DATE,userpk,IS_DOWN)
			   values(newid(),@cust_guid,@billNo,CONVERT(varchar(10),GETDATE(),120),5,@use_price*-1,0,CONVERT(varchar(20),GETDATE(),120),'498102A3-74D9-4651-BC74-A2428E58C3C4',0)
			   --更新計費明細
			   update change_db set is_js=1
			   from change_db db
			   left join device_info dev on dev.device_guid=db.device_guid
			   left join rooms_man rm on rm.rm_newid = dev.cust_guid
               left join cust_info cus on cus.cust_guid = rm.cust_guid
			   where (db.is_js is null or db.is_js=0)
			   and end_time<=convert(varchar(10),getdate(),120)
			   and cus.cust_guid=@cust_guid;
           end
	    FETCH NEXT FROM N_CUR_SDJS INTO @cust_guid
	END
	CLOSE N_CUR_SDJS
	DEALLOCATE N_CUR_SDJS	
end
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章