use [crm01]go/****** object: storedprocedure [dbo].[account3yearstrade] script date: 07/15/2015 08:34:37 ******/
set ansi_nulls on
goset quoted_identifier on
goalter procedure [dbo].[account3yearstrade] as
declare @accountid uniqueidentifier ,
@yt_total_price money ,
@opportunityid uniqueidentifier ,
@yt_invoice_date int ,
@yt_lastyeartrading money ,
@yt_toptwoannualturnover money ,
@yt_topthreeannualturnover money ,
@nowdate int
--宣告乙個游標mycursor,select語句中引數的個數必須要和從游標取出的變數名相同
declare mycursor cursor
for select accountid from accountbase where statecode=0
select @nowdate=datepart(year,getdate())
--開啟游標
open mycursor
--從游標裡取出資料賦值到我們剛才宣告的2個變數中
fetch next from mycursor into @accountid
--判斷游標的狀態
-- 0 fetch語句成功
---1 fetch語句失敗或此行不在結果集中
---2 被提取的行不存在
while ( @@fetch_status = 0 )
begin
set @yt_lastyeartrading = 0
set @yt_toptwoannualturnover = 0
set @yt_topthreeannualturnover = 0
declare mycursortwo cursor
for
with childaccount(accountid,parentaccountid) as
( select accountid,parentaccountid from accountbase where accountid=@accountid
union all
select a.accountid,a.parentaccountid from accountbase a,childaccount b
where a.parentaccountid = b.accountid
)select yt_total_price,datepart(year,yt_invoice_date),opportunityid from opportunity
where yt_arrive in(select accountid from childaccount) and yt_status=100000002
open mycursortwo
fetch next from mycursortwo into @yt_total_price,@yt_invoice_date,@opportunityid
while( @@fetch_status = 0 )
begin
if(@yt_invoice_date=@nowdate-1)
begin
set @yt_lastyeartrading = @yt_lastyeartrading + isnull(@yt_total_price,0.0000)
endelse if(@yt_invoice_date=@nowdate-2)
begin
set @yt_toptwoannualturnover = @yt_toptwoannualturnover + isnull(@yt_total_price,0.0000)
endelse if(@yt_invoice_date=@nowdate-3)
begin
set @yt_topthreeannualturnover = @yt_topthreeannualturnover + isnull(@yt_total_price,0.0000)
endfetch next from mycursortwo into @yt_total_price,@yt_invoice_date,@opportunityid
endclose mycursortwo
deallocate mycursortwo
update account
set yt_lastyeartrading = @yt_lastyeartrading,yt_lastyeartrading_base = @yt_lastyeartrading,yt_toptwoannualturnover = @yt_toptwoannualturnover,
yt_toptwoannualturnover_base = @yt_toptwoannualturnover,yt_topthreeannualturnover = @yt_topthreeannualturnover,yt_topthreeannualturnover_base = @yt_topthreeannualturnover
where accountid = @accountid
--用游標去取下一條客戶
fetch next from mycursor into @accountid
end
--關閉游標
close mycursor
--撤銷游標
deallocate mycursor
ORACLE游標 遞迴查詢 子查詢與批量更新示例
建立臨時表 create table tj org new deptcode nvarchar2 255 orgdesc nvarchar2 255 organtype nvarchar2 255 levelfact number 6 parentdeptcode nvarchar2 255 tab...
查詢首頁客戶數
1 13888 0 5085 2 57 null 149 19179 select rownum r,from tkhxx tkhxx,xtdc.tfx kh srzhzk b where tkhxx.id b.khid and tkhxx.id not in select m.id from tk...
android客戶端中Sql的遞迴查詢
公司業務需要查詢通訊錄部門資料 就想到了遞迴查詢了一下 sql也可以直接遞迴查詢 第乙個查詢為定點成員,定點成員只是乙個返回有效表的查詢,用於遞迴的基礎或定位點 第二個查詢被稱為遞迴成員,使該查詢成為遞迴成員的是對遞迴引用時觸發 遞迴表.id與該錶的pid 遞迴查詢沒有顯式的遞迴終止條件,只有當第二...