一个Sql Server 的游标与循环嵌套的存储过程用例
准备代码
--创建表
CREATE TABLE everyoneAVG
(
ID int primary key identity(1,1),
AccNo INT,
AVGTime INT,
AddTimes INT
);
DROP TABLE everyoneAVG;
SELECT ID,AccNo AS ‘用户号‘,AVGTime/60 AS ‘平均充值时间间隔(小时)‘,AddTimes AS ‘总充值次数‘
FROM everyoneAVG
ORDER BY AVGTime/60 DESC;
DELETE everyoneAVG;
功能需求
查询出一个时间段内每个人的平均充值时间间隔
实现代码
CREATE PROCEDURE P_getAVGAddTime
AS
BEGIN
DECLARE
@AccountNo INT, --账户号
@AVGTime INT, --每个人平均充值间隔时间(分钟)
@AddTimes INT, --每个人总充值次数(忽略十分钟内的充值)
@upConsumeTime DATETIME, --前一次成交时间
@ConsumeTime DATETIME, --当前成交时间
@TempTime INT --临时记录累加的间隔时间(分钟)
--声明用户号游标
DECLARE allAcc_cursor CURSOR FOR
SELECT top 99.9999 percent AccountNo
FROM [CASH].[dbo].[tb_Customer]
ORDER BY AccountNo
OPEN allAcc_cursor --打开游标
FETCH NEXT FROM allAcc_cursor --获取游标下一行数据
INTO @AccountNo --使变量获取当前游标指定行的账户号
-----------外部游标,ORDER BY AccountNo
WHILE(@@FETCH_STATUS=0)
BEGIN
SET @TempTime=0
SET @AVGTime=0 --每个人平均充值时间赋初值
SET @AddTimes=0 --每个人充值次数赋初值
SET @upConsumeTime=‘2017-11-09 00:00:00.000‘
DECLARE ConsumeTime_Cursor CURSOR FOR --声明成交时间
--充值记录查询
SELECT top 99.9999 percent ConsumeTime
FROM [CASH].[dbo].[tb_inf]
WHERE [email protected] AND GrpNo=98 AND ExChgDate>=‘2017-11-09 00:00:00.000‘ AND ExChgDate<=‘2018-04-16 00:00:00.000‘
ORDER BY ConsumeTime
OPEN ConsumeTime_Cursor --打开成交时间游标
FETCH NEXT FROM ConsumeTime_Cursor --获取下一行数据
INTO @ConsumeTime
WHILE(@@FETCH_STATUS=0)
BEGIN
--首次充值处理
IF(@upConsumeTime=‘2017-11-09 00:00:00.000‘)
BEGIN
SET @[email protected]
SET @[email protected]+1
END
ELSE
IF(DATEDIFF(MINUTE,@upConsumeTime,@ConsumeTime)<10) ----十分钟内的充值时间忽略
BEGIN
SET @[email protected]
END
ELSE
BEGIN
SET @[email protected]+1 --充值次数累加
SET @[email protected]+DATEDIFF(MINUTE,@upConsumeTime,@ConsumeTime) --充值时间间隔累加
SET @[email protected]
END
FETCH NEXT FROM ConsumeTime_Cursor --获取下一行数据
INTO @ConsumeTime
END
--仅充值一次或从未充值
IF(@AddTimes=1)
BEGIN
SET @AVGTime=0
END
ELSE
BEGIN
SET @[email protected]/(@AddTimes-1)
END
--将得到的平均值存入临时表
BEGIN
INSERT INTO [CASH].[dbo].[everyoneAVG]
VALUES(@AccountNo,@AVGTime,@AddTimes)
END
CLOSE ConsumeTime_Cursor --关闭内部游标
DEALLOCATE ConsumeTime_Cursor --释放内部游标
FETCH NEXT FROM allAcc_cursor --获取游标下一行数据
INTO @AccountNo --使变量获取当前游标指定行的账户号
END
CLOSE allAcc_cursor --关闭外部游标
DEALLOCATE allAcc_cursor --释放外部游标
END
GO
一个Sql Server 的游标与循环嵌套的存储过程用例
原文地址:http://blog.51cto.com/13710467/2105344
时间: 2024-10-20 09:55:45