/*
Last Edit 2022-03-03
温馨提示:本脚本适用于从联机写卡通用版6.1.0及以上版本升级到通用版6.19.0.125

TABLE_ADD_1 增加支付表T_Payment
TABLE_ADD_2 删除并重新创建T_R_Report报表，重建报表 T_R_Report
TABLE_ADD_3  删除并重新创建T_R_Dict报表，重建报表 T_R_Dict
TABLE_ADD_4 增加表T_B_BankCode 
TABLE_ADD_5 增加表T_B_BankCardCode
TABLE_ADD_6 增加表T_B_EmpFace  
TABLE_ADD_7 增加重复流水表T_C_REC_Repeat  
TABLE_ADD_8 增加日志收缩记录表T_B_DbShinkHistory 
TABLE_ADD_9 增加待处理流水表T_C_PendingConsRec 
TABLE_ADD_10增加过期流水表T_C_Rec_OverdueRec
TABLE_ADD_11增加处理结果表T_C_middle_Step1
TABLE_ADD_12增加处理结果表T_C_middle_Step2
TABLE_ADD_13增加 保存账户每日结余表处理到哪天了T_C_SumEmpDealByDay
TABLE_ADD_14 增加缓存表 T_C_CashEmp
TABLE_ADD_15 增加缓存表 T_C_CashEmpEx
TABLE_ADD_16 增加批量操作记录表T_B_OperateObject


TABLE_EDIT_1 修改操作员表T_B_Employee 
TABLE_EDIT_2 修改账户结余汇总表T_C_SysAccontdDay
TABLE_EDIT_3 钱包表T_B_PurseCode增加字段 fMaxMoney 卡片上限金额
TABLE_EDIT_4 T_C_middle_Step1增加字段
TABLE_EDIT_5 T_C_middle_Step2增加字段
TABLE_EDIT_6 T_B_Tasks增加字段  20220303


ADD_CULUM_1 汇总表T_C_SumEmp_XXXXXX增加字段fLimitConsCount、fLimitConsMoney
ADD_CULUM_2 汇总表T_C_ConsEmp_XXXXXX增加字段fLimitMealXXCount、fLimitMealXXMoney
ADD_CULUM_3 T_C_CashdataXX 增加字段fPosID
ADD_CULUM_4 设备表增加是否为转款机字段fTransPayPos
ADD_CULUM_5 未确认流水表T_C_Rec_Unconfirmed增加外部订单号字段

VALUES_ADD_1 报表T_R_Report,T_R_Dict

VIEW_EDIT_1 修改视图V_B_Employee 
VIEW_EDIT_2 修改视图V_B_Pos
VIEW_EDIT_3 修改视图V_C_SUM_OPER
VIEW_EDIT_4 修改视图V_C_SUM_Pos 

PROC_ADD_1 增加后台处理个人消费汇总存储过程SP_GetEmpSumInfo_Backstage
PROC_ADD_2 增加界面处理个人消费汇总存储过程SP_GetEmpSumInfo_Interface

PROC_EDIT_1 写流水存储过程修改UP_InsertOnLineRecord  20220107
PROC_EDIT_2 修改账户每日汇总存储过程UP_MakeSysAccontByday
PROC_EDIT_3 修改存储过程SP_Wst_CheckSumEmpTable，增加字段
PROC_EDIT_4 修改存储过程SP_Wst_CheckConsEmpTable，增加字段
PROC_EDIT_5 修改存储过程SP_Cash_CheckRecTable增加fPosID
PROC_EDIT_6 修改存储过程SP_GetEmpSumInfo
PROC_EDIT_7 创建流水表SP_Wst_CheckRecTable
PROC_EDIT_8 修改存储过程UP_R_CheckTime
PROC_EDIT_9 修改存储过程SP_CreateCommonRecsView
PROC_EDIT_10 增加创建菜品流水表UP_CheckDishRecTable
PROC_EDIT_11 增加菜品流水表查询UP_R_CheckTime
PROC_EDIT_12 增加插入菜品流水UP_InsertDishRec
PROC_EDIT_13 增加SP_SetCardHis
PROC_EDIT_14 增加存储过程UP_InsertOnLineRecord_Step1  20220107
PROC_EDIT_15 增加存储过程UP_InsertOnLineRecord_Step2 
PROC_EDIT_16 增加存储过程UP_InsertOnLineRecord_Step3 
PROC_EDIT_17 增加存储过程UP_MakeSumEmpByday
PROC_EDIT_18 增加存储过程UP_RecordBAWList


REPORT_ADD_1 新增身份消费统计报表UP_Report_Cns_Total_ManTypeMeal
REPORT_ADD_2 新增营业分组报表 UP_Report_Cns_Total_DeptBZ
REPORT_ADD_3 新增菜品流水汇总UP_Report_Cns_DishRecSum
REPORT_ADD_4 新增菜品流水明细UP_Report_Cns_DishRecDetail


REPORT_EDIT_1 出纳日报表UP_Report_Cns_Total_CashDays
REPORT_EDIT_2 出纳月报表UP_Report_Cns_Total_CashMonth
REPORT_EDIT_3 出纳阶段报表UP_Report_Cns_Total_CashStaged
REPORT_EDIT_4 营业日报表UP_Report_Cns_ConsDay
REPORT_EDIT_5 营业月报表UP_Report_Cns_ConsMonth
REPORT_EDIT_6 营业阶段报表UP_Report_Cns_ConsSpace
REPORT_EDIT_7 流水记录报表增加钱包名称字段显示
REPORT_EDIT_8 修改补助领取报表UP_Report_sub_detail_AlreadySubsidy
REPORT_EDIT_9 修改账户查询报表UP_Report_Cns_Account
REPORT_EDIT_10修改账户结余汇总表 UP_Report_SysAccount
REPORT_EDIT_11 修改出纳阶段报表（按钱包）UP_Report_Cns_Total_CashStagedByPurse 
REPORT_EDIT_12 修改报表UP_Report_Cns_Total_CashMonthDay 
REPORT_EDIT_13 修改报表UP_Report_detail_OperatorLog 

*/


--修改平台脚本版本号
if exists(select  * FROM T_B_SysParam where fParamName='PlatScriptVersion')
begin
  update T_B_SysParam set fParamValue='20220303115638' where fParamName='PlatScriptVersion'
end
else
begin
   insert into T_B_SysParam(fParamName,fParamValue,fParamType,fRestrict,fExplain)
   values('PlatScriptVersion','20220303115638','String','','平台脚本版本号')
end
--修改报表脚本版本号
if exists(select  * FROM T_B_SysParam where fParamName='ReportScriptVersion')
begin
  update T_B_SysParam set fParamValue='20210604173200' where fParamName='ReportScriptVersion'
end
else
begin
   insert into T_B_SysParam(fParamName,fParamValue,fParamType,fRestrict,fExplain)
   values('ReportScriptVersion','20210604173200','String','','报表脚本版本号')
end
GO

--修改最后登录时间
if not exists(select  * FROM T_B_SysParam where fParamName='LastRunTime')
begin
	insert into T_B_SysParam(fParamName,fParamValue,fParamType,fRestrict,fExplain)
	values('LastRunTime','0','Datetime','','最后登录时间')
end
GO


--TABLE_ADD_1 增加支付表T_Payment
if not exists (select * from sysobjects where id = object_id(N'[T_Payment]') and OBJECTPROPERTY(id, N'IsUserTable') = 1) 
begin
CREATE TABLE [dbo].[T_Payment](
	[fOrderWater] [int] IDENTITY(1,10000) NOT NULL,
	[fPosID] [int] NOT NULL DEFAULT 0 ,
	[fPayType] [int] NOT NULL  DEFAULT 0 ,
	[fRequestTime] [datetime] NOT NULL,
	[fPayMoney] [money] NOT NULL,
	[fRequestJson] [varchar](500) NULL,
	[fStatus] [int] NOT NULL,
	[fResponseTime] [datetime] NULL,
	[fMsgCode] [varchar](10) NULL,
	[fMsgInfo] [varchar](100) NULL,
	[fResult] [int] NULL,
	[fCodeURL] [varchar](100) NULL,
	[fPrepayID] [varchar](20) NULL,
	[fAppID] [varchar](20) NULL,
	[fPartnerid] [varchar](20) NULL,
	[outTradeNo] [varchar](64) NULL,
 CONSTRAINT [PK_T_Payment_1] PRIMARY KEY CLUSTERED 
(
	[fOrderWater] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
end
GO

--TABLE_ADD_2 删除并重新创建T_R_Report报表，重建报表 T_R_Report
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[T_R_Report]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE [dbo].[T_R_Report]
GO
CREATE TABLE [dbo].[T_R_Report](
	[fReportID] [int] NOT NULL,
	[fReportName] [varchar](40) NULL,
	[fReportProc] [varchar](60) NULL,
	[fReportType] [int] NULL,
	[fGroupID] [varchar](25) NULL,
	[ffr3fileName] [varchar](50) NULL,
	[fDisPlay] [int] NULL,
	[fDefaultDis] [int] NULL,
	[fPrintDirection] [bit] NULL,
	[fColUnDis] [varchar](20) NULL,
	[fColFix] [int] NULL,
	[fTotleDis] [varchar](1000) NULL,
	[fHide] [bit] NULL,
	[fBPageDis] [bit] NULL DEFAULT(0),
	[fRemark] [varchar](200) NULL,
 CONSTRAINT [PK_T_R_Report] PRIMARY KEY CLUSTERED 
(
	[fReportID] ASC
) ON [PRIMARY]
) ON [PRIMARY]

GO
--TABLE_ADD_3  删除并重新创建T_R_Dict报表，重建报表 T_R_Dict
IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[T_R_Dict]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
DROP TABLE [dbo].[T_R_Dict]
GO

CREATE TABLE [dbo].[T_R_Dict](
	[fDictID] [int] IDENTITY(1,1) NOT NULL,
	[fDictType] [int] NULL,
	[fDictName] [varchar](40) NULL,
	[fSerialNO] [int] NULL,
	[fDisplayName] [varchar](40) NULL,
	[fFootType] [int] NOT NULL,
	[fDictContent] [varchar](100) NULL,
	[fMask] [varchar](40) NULL,
	[fMax] [varchar](50) NULL,
	[fMin] [varchar](50) NULL,
	[fDictDefault] [varchar](50) NULL,
	[fIsCheck] [bit] NULL,
	[fIsPrint] [bit] NULL,
	[fIsScript] [bit] NULL,
	[fReportID] [int] NULL,
	[fRemark] [varchar](100) NULL,
 CONSTRAINT [PK_T_R_Dict] PRIMARY KEY CLUSTERED 
(
	[fDictID] ASC
) ON [PRIMARY]
) ON [PRIMARY]
GO
--TABLE_ADD_4 增加表T_B_BankCode
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[T_B_BankCode]') AND type in (N'U'))
DROP TABLE [dbo].[T_B_BankCode]
GO
CREATE TABLE [dbo].[T_B_BankCode](
	[fKeyId] [int] IDENTITY(1,1) NOT NULL,
	[fBankCode] [varchar](8) NOT NULL,
	[fBankName] [varchar](100) NOT NULL,
	[fBankAddr] [varchar](100) NOT NULL,
	[fBankPort] [varchar](100) NOT NULL,
	[fDzAddr] [varchar](200) NOT NULL,
	[fDzTime] [datetime] NOT NULL,
	[fDzbz] [smallint] NOT NULL,
	[fYDzbz] [smallint] NOT NULL,
	[fYdzTime] [datetime] NULL,
	[fXybz] [smallint] NOT NULL,
	[fReServe] [varchar](100) NULL,
	[fHandDzBz] [smallint] NOT NULL
)
GO
--TABLE_ADD_5 增加表T_B_BankCardCode
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[T_B_BankCardCode]') AND type in (N'U'))
DROP TABLE [dbo].[T_B_BankCardCode]
GO
CREATE TABLE [dbo].[T_B_BankCardCode](
	[fKeyId] [int] IDENTITY(1,1) NOT NULL,
	[fBankCode] [varchar](8) NOT NULL,
	[fCardCode] [varchar](6) NOT NULL,
	[fXyBz] [smallint] NOT NULL,
	[fRemark] [varchar](100) NULL
)
GO

--TABLE_ADD_6 增加表T_B_EmpFace
if not exists (select * from sysobjects where id = object_id(N'[T_B_EmpFace]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
 begin
	CREATE TABLE [dbo].[T_B_EmpFace](
		[fACcountid] [varchar](18) NOT NULL,
		[fEmpFace] [varchar](max) NULL
	) ON [PRIMARY]
end
GO

--TABLE_ADD_7 增加重复流水表T_C_REC_Repeat

 if not exists(select  * from sys.all_objects where type='U'  and name='T_C_REC_Repeat')
 begin
 CREATE TABLE [T_C_REC_Repeat] (    
  fAutoID int IDENTITY (1, 1) NOT NULL,    
  fPurseID INT,      --钱包编号        
  fFlowType INT,      --流水类型        
  fRecType INT,      --交易类型        
  fUserCardID VARCHAR(16),   --用户卡号(物理卡号/应用序列号)        
  fPosID INT,       --交易终端号        
  fCreateTime DATETIME,    --交易时间        
  fRecvTime DATETIME,     --入库时间        
  fAmount Numeric(18,2),    --交易额        
  fDiscount Numeric(18,2),   --折扣额        
  fSourceID INT,      --来源        
  fTaskID INT,      --任务编号        
  fOperID INT,      --操作员编号         
  fFee1 Numeric(18,2),    --其他费用1(手续费)        
  fFee2 Numeric(18,2),    --其他费用2(卡费)        
  fFee3 Numeric(18,2),    --其他费用3(押金)        
  fFee4 Numeric(18,2),    --其他费用4(管理费)        
  fOffTranNo INT,      --卡脱机交易序号        
  fPosTranNo INT,      --终端联机交易序号         
  fPosOffTranNo INT,     --终端脱机交易序号        
  ffRecKey VARCHAR(200),    --数据校验Key值    
  ffExternalOrder VARCHAR(100)
  )  

  end
  go
  
--TABLE_ADD_8 增加增加日志收缩记录表T_B_DbShinkHistory 
if not exists(select  * from sys.all_objects where type='U' and name='T_B_DbShinkHistory')
begin
   create table T_B_DbShinkHistory
   (
     fKeyID [int] IDENTITY(1,1) NOT NULL,
     fOperDate datetime,
     fStationID varchar(2),
     fOperID int
   )
end
go
--TABLE_ADD_9 增加待处理流水表T_C_PendingConsRec 
if not exists(select  * from sys.all_objects where type='U' and name='T_C_PendingConsRec')
begin
   create table T_C_PendingConsRec
   (
     fKeyID [int] IDENTITY(1,1) NOT NULL,
     fPurseID INT NULL,                   --钱包编号        
					fFlowType INT NULL,                  --流水类型        
					fRecType INT NULL,                   --交易类型        
					fUserCardID VARCHAR(16) NULL,        --用户卡号(物理卡号/应用序列号)        
					fPosID INT NULL,                     --交易终端号        
					fCreateTime DATETIME NULL,           --交易时间        
					fRecvTime DATETIME NULL,             --入库时间        
					fAmount Numeric(18,2) NULL,          --交易额        
					fDiscount Numeric(18,2) NULL,        --折扣额        
					fSourceID INT NULL,                  --来源        
					fTaskID INT NULL,                    --任务编号        
					fOperID INT NULL,                    --操作员编号         
					fFee1 Numeric(18,2) NULL,            --其他费用1(手续费)        
					fFee2 Numeric(18,2) NULL,            --其他费用2(卡费)        
					fFee3 Numeric(18,2) NULL,            --其他费用3(押金)        
					fFee4 Numeric(18,2) NULL,            --其他费用4(管理费)        
					fOffTranNo INT NULL,                 --卡脱机交易序号        
					fPosTranNo INT NULL,                 --终端联机交易序号         
					fPosOffTranNo INT NULL,              --终端脱机交易序号        
					ffRecKey VARCHAR(200) NULL,          --数据校验Key值    
					ffExternalOrder VARCHAR(100) NULL,   --外部单号
					fDealState int not null default 0,    --是否处理了此条记录 0-未处理 1-已处理、
					fDealTime datetime null
   )
end
GO
--TABLE_ADD_10增加过期流水表T_C_Rec_OverdueRec
if not exists(select  * from sys.all_objects where type='U' and name='T_C_Rec_OverdueRec')
BEGIN
 CREATE TABLE [dbo].[T_C_Rec_OverdueRec](
	[fAutoID] [int] IDENTITY(1,1) NOT NULL,
	[fAccountID] [varchar](18) NOT NULL,
	[fSerialNo] [varchar](30) NOT NULL,
	[fPurseID] [int] NOT NULL,
	[fRecType] [int] NOT NULL,
	[fPosID] [varchar](5) NOT NULL,
	[fCreateTime] [datetime] NOT NULL,
	[fRecvTime] [datetime] NOT NULL,
	[fAmount] [numeric](9, 2) NOT NULL,
	[fDiscount] [numeric](9, 2) NULL,
	[fSourceID] [int] NOT NULL,
	[fCardTranNo] [int] NOT NULL,
	[fPosTranNo] [int] NULL,
	[fMealID] [varchar](3) NULL,
	[fRecKey] [varchar](200) NULL,
	[fExternalOrder] [varchar](100) NOT NULL,
 CONSTRAINT [PK_T_C_Rec_OverdueRec] PRIMARY KEY CLUSTERED 
(
	[fCreateTime] ASC,
	[fAccountID] ASC,
	[fSerialNo] ASC,
	[fPurseID] ASC,
	[fRecType] ASC,
	[fAmount] ASC,
	[fPosID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
ALTER TABLE [dbo].[T_C_Rec_OverdueRec] ADD  DEFAULT ('') FOR [fExternalOrder]
END
GO

--TABLE_ADD_11增加处理结果表T_C_middle_Step1

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[T_C_middle_Step1]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[T_C_middle_Step1](
 	[fKeyID] [bigint] IDENTITY(1,1) NOT NULL PRIMARY KEY,
  [fPurseID] [INT],      --钱包编号              
  [fRecType] [INT],      --交易类型
  [fAccountID] [VARCHAR](10),        
  [fUserCardID] [VARCHAR](16),   --用户卡号(物理卡号/应用序列号)        
  [fPosID] [INT],       --交易终端号 
  [fStationID] [VARCHAR](10), 
  [fMealID] [VARCHAR](10),      
  [fCreateTime] [DATETIME],    --交易时间        
  [fRecvTime] [DATETIME],     --入库时间 
  [fOldMoney] [Numeric](18,2),       
  [fAmount] [Numeric](18,2),    --交易额        
  [fBalance] [Numeric](18,2),
  [fDiscount] [Numeric](18,2),   --折扣额            
  [fOperID] [INT],      --操作员编号         
  [fFee1] [Numeric](18,2),    --其他费用1(手续费)        
  [fFee2] [Numeric](18,2),    --其他费用2(卡费)        
  [fFee3] [Numeric](18,2),    --其他费用3(押金)        
  [fFee4] [Numeric](18,2),    --其他费用4(管理费)   
  [fLimitCountEnabled] [bit],--Pos机是否限次
  [fFlowType] [INT],      --流水类型                                
  [fSourceID] [INT],      --来源        
  [fTaskID] [INT],      --任务编号        
  [fOffTranNo] [INT],      --卡脱机交易序号        
  [fPosTranNo] [INT],      --终端联机交易序号         
  [fPosOffTranNo] [INT],     --终端脱机交易序号        
  [ffRecKey] [VARCHAR](200),    --数据校验Key值    
  [ffExternalOrder] [VARCHAR](100), --外部单号
  [fIsRepeatWater] [INT], --是否重复流水 0-否，1-是
  [fIsPendingConsRec] [int], --是否是待处理流水  0-否，1-是    
) ON [PRIMARY]
END
GO

--TABLE_ADD_12增加处理结果表T_C_middle_Step2

IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[T_C_middle_Step2]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
BEGIN
CREATE TABLE [dbo].[T_C_middle_Step2](
	[fKeyID] [bigint] IDENTITY(1,1) NOT NULL PRIMARY KEY,
 [fPurseID] [INT],      --钱包编号              
 [fRecType] [INT],      --交易类型        
 [fAccountID] [VARCHAR](16),   --账号      
 [fPosID] [INT],       --交易终端号        
 [fMealID] [VARCHAR](3),    --餐次       
 [fRecvTime] [DATETIME],     --入库时间        
 [fOldMoney] [Numeric](18,2),    --原余额
 [fAmount] [Numeric](18,2),    --交易额  
 [fBalance] [Numeric](18,2),    --现余额        
 [fDiscount] [Numeric](18,2),   --折扣额              
 [fOperID] [INT],      --操作员编号         
 [fFee1] [Numeric](18,2),    --其他费用1(手续费)        
 [fFee2] [Numeric](18,2),    --其他费用2(卡费)        
 [fFee3] [Numeric](18,2),    --其他费用3(押金)        
 [fFee4] [Numeric](18,2),    --其他费用4(管理费) 
 [fLimitCountEnabled] bit,--Pos机是否限次
 
 [fUserCardID] [VARCHAR](16),   --用户卡号(物理卡号/应用序列号)        
	[fStationID] [VARCHAR](10),      
	[fCreateTime] [DATETIME],    --交易时间                                       
	[fFlowType] [INT],      --流水类型                                
	[fSourceID] [INT],      --来源        
	[fTaskID] [INT],      --任务编号        
	[fOffTranNo] [INT],      --卡脱机交易序号        
	[fPosTranNo] [INT],      --终端联机交易序号         
	[fPosOffTranNo] [INT],     --终端脱机交易序号        
	[ffRecKey] [VARCHAR](200),    --数据校验Key值    
	[ffExternalOrder] [VARCHAR](100), --外部单号        
) ON [PRIMARY]
END
GO

--TABLE_ADD_13增加 保存账户每日结余表处理到哪天了T_C_SumEmpDealByDay
if not exists(SELECT  * FROM sys.all_objects WHERE name='T_C_SumEmpDealByDay')
begin
  create table T_C_SumEmpDealByDay
  (
    fKeyID int IDENTITY(1,1)NOT NULL,
    fDate varchar(10),
    fCreateTime datetime,
    fOpreID int
  )
end
go

--TABLE_ADD_14 增加缓存表 T_C_CashEmp

--按餐次、天
if not exists(select  * from sys.all_objects where name='T_C_CashEmp')
begin
  create table T_C_CashEmp
  (
	  fkey varchar(50) not null primary key,      --关键值（类别+账号+钱包号+日期+餐次）
	  faccountID varchar(10) null,    --账号
	  fdate datetime,                 --日期
	  fpurseID int,                   --钱包号
	  fmealID varchar(3),             --餐次
	  famount	numeric(9,2),           --累计消费金额
	  fcount	 int,                    --累计消费次数
	  famountLimit	numeric(9,2),      --累计消费金额（作为限额依据）
	  fcountLimit	 int,               --累计消费次数（作为限额依据）
	  fRver   timestamp               --行版本戳
  )
end
go
--TABLE_ADD_15 增加缓存表 T_C_CashEmpEx
--按周、月、年
if not exists(select  * from sys.all_objects where name='T_C_CashEmpEx')
begin
  create table T_C_CashEmpEx
  (
	  fkey varchar(50) not null primary key,      --关键值（类别+账号+钱包号+周\月\年+餐次）
	  ftype varchar(2),                      --类别：周、月、年
	  faccountID varchar(10) null,    --账号
	  fvalue  int,                     -- 周202106 月20210600  年20210000
	  fpurseID int,                   --钱包号
	  fmealID varchar(3),             --餐次
	  famount	numeric(9,2),           --累计消费金额
	  fcount	 int,                    --累计消费次数
	  famountLimit	numeric(9,2),      --累计消费金额（作为限额依据）
	  fcountLimit	 int,               --累计消费次数（作为限额依据）
	  fRver   timestamp               --行版本戳
  )
end
go
--TABLE_ADD_16 增加批量操作记录表T_B_OperateObject
if not exists(select  * from sys.all_objects where name='T_B_OperateObject')
begin  
create table T_B_OperateObject
  (
    fOperType int,
    fAccountID varchar(10),
    fSerialNo varchar(10),
    fPurseCode int,
    fCreateTime datetime,
    fRemark varchar(100)
  )
END  
GO

--TABLE_EDIT_1 修改操作员表T_B_Employee 

if not EXISTS(select id from syscolumns where name='fIsBind' and [id]=object_id('T_B_Employee')) 
  ALTER TABLE T_B_Employee add fIsBind int not null default 0
if not EXISTS(select id from syscolumns where name='fBankNo' and [id]=object_id('T_B_Employee')) 
  ALTER TABLE T_B_Employee add fBankNo varchar(40) 
if not EXISTS(select id from syscolumns where name='fParentName' and [id]=object_id('T_B_Employee')) 
  ALTER TABLE T_B_Employee add fParentName varchar(20) 
if not EXISTS(select id from syscolumns where name='fLastOperateTime' and [id]=object_id('T_B_Employee')) 
  ALTER TABLE T_B_Employee ADD fLastOperateTime datetime 
if not exists(select  * from sys.all_columns where object_id=object_id('T_B_Employee') and name='fHaveKhWater')
  ALTER TABLE T_B_Employee add fHaveKhWater int not null default 0
if not exists(select  * from sys.all_columns where object_id=object_id('T_B_Employee') and name='rver')
  ALTER TABLE T_B_Employee add rver timestamp not null
go

--TABLE_EDIT_2 修改账户结余汇总表T_C_SysAccontdDay 增加计次原余额 ，计次现余额
if (select id from syscolumns where name='fOldAcountMoneyJC' and [id]=object_id('T_C_SysAccontdDay')) is null
  ALTER TABLE T_C_SysAccontdDay ADD fOldAcountMoneyJC INT not null default 0
if (select id from syscolumns where name='fNewAcountMoneyJC' and [id]=object_id('T_C_SysAccontdDay')) is null
  ALTER TABLE T_C_SysAccontdDay ADD fNewAcountMoneyJC INT not null default 0
if (select id from syscolumns where name='fConsMoneyJC' and [id]=object_id('T_C_SysAccontdDay')) is null
  ALTER TABLE T_C_SysAccontdDay ADD fConsMoneyJC INT not null default 0 
if (select id from syscolumns where name='fSbCountJC' and [id]=object_id('T_C_SysAccontdDay')) is null
  ALTER TABLE T_C_SysAccontdDay ADD fSbCountJC INT not null default 0  
if (select id from syscolumns where name='fSbtlSumJC' and [id]=object_id('T_C_SysAccontdDay')) is null
  ALTER TABLE T_C_SysAccontdDay ADD fSbtlSumJC INT not null default 0 
if (select id from syscolumns where name='fSbClearCountJC' and [id]=object_id('T_C_SysAccontdDay')) is null
  ALTER TABLE T_C_SysAccontdDay ADD fSbClearCountJC INT not null default 0  
if (select id from syscolumns where name='fSbClearSumJC' and [id]=object_id('T_C_SysAccontdDay')) is null
  ALTER TABLE T_C_SysAccontdDay ADD fSbClearSumJC INT not null default 0
if (select id from syscolumns where name='fJcCountJC' and [id]=object_id('T_C_SysAccontdDay')) is null
  ALTER TABLE T_C_SysAccontdDay ADD fJcCountJC INT not null default 0  
if (select id from syscolumns where name='fJctlSumJC' and [id]=object_id('T_C_SysAccontdDay')) is null
  ALTER TABLE T_C_SysAccontdDay ADD fJctlSumJC INT not null default 0
if (select id from syscolumns where name='fSaveCountJC' and [id]=object_id('T_C_SysAccontdDay')) is null
  ALTER TABLE T_C_SysAccontdDay ADD fSaveCountJC INT not null default 0  
if (select id from syscolumns where name='fSaveMoneyJC' and [id]=object_id('T_C_SysAccontdDay')) is null
  ALTER TABLE T_C_SysAccontdDay ADD fSaveMoneyJC INT not null default 0
if (select id from syscolumns where name='fTakeCountJC' and [id]=object_id('T_C_SysAccontdDay')) is null
  ALTER TABLE T_C_SysAccontdDay ADD fTakeCountJC INT not null default 0  
if (select id from syscolumns where name='fTakeMoneyJC' and [id]=object_id('T_C_SysAccontdDay')) is null
  ALTER TABLE T_C_SysAccontdDay ADD fTakeMoneyJC INT not null default 0 
    
if (select id from syscolumns where name='fOldAcountMoneyJC' and [id]=object_id('T_C_SysAccontdToDay')) is null
  ALTER TABLE T_C_SysAccontdToDay ADD fOldAcountMoneyJC INT not null default 0
if (select id from syscolumns where name='fNewAcountMoneyJC' and [id]=object_id('T_C_SysAccontdToDay')) is null
  ALTER TABLE T_C_SysAccontdToDay ADD fNewAcountMoneyJC INT not null default 0
if (select id from syscolumns where name='fConsMoneyJC' and [id]=object_id('T_C_SysAccontdToDay')) is null
  ALTER TABLE T_C_SysAccontdToDay ADD fConsMoneyJC INT not null default 0
if (select id from syscolumns where name='fSbCountJC' and [id]=object_id('T_C_SysAccontdToDay')) is null
  ALTER TABLE T_C_SysAccontdToDay ADD fSbCountJC INT not null default 0  
if (select id from syscolumns where name='fSbtlSumJC' and [id]=object_id('T_C_SysAccontdToDay')) is null
  ALTER TABLE T_C_SysAccontdToDay ADD fSbtlSumJC INT not null default 0
if (select id from syscolumns where name='fSbClearCountJC' and [id]=object_id('T_C_SysAccontdToDay')) is null
  ALTER TABLE T_C_SysAccontdToDay ADD fSbClearCountJC INT not null default 0  
if (select id from syscolumns where name='fSbClearSumJC' and [id]=object_id('T_C_SysAccontdToDay')) is null
  ALTER TABLE T_C_SysAccontdToDay ADD fSbClearSumJC INT not null default 0
if (select id from syscolumns where name='fJcCountJC' and [id]=object_id('T_C_SysAccontdToDay')) is null
  ALTER TABLE T_C_SysAccontdToDay ADD fJcCountJC INT not null default 0  
if (select id from syscolumns where name='fJctlSumJC' and [id]=object_id('T_C_SysAccontdToDay')) is null
  ALTER TABLE T_C_SysAccontdToDay ADD fJctlSumJC INT not null default 0
if (select id from syscolumns where name='fSaveCountJC' and [id]=object_id('T_C_SysAccontdToDay')) is null
  ALTER TABLE T_C_SysAccontdToDay ADD fSaveCountJC INT not null default 0  
if (select id from syscolumns where name='fSaveMoneyJC' and [id]=object_id('T_C_SysAccontdToDay')) is null
  ALTER TABLE T_C_SysAccontdToDay ADD fSaveMoneyJC INT not null default 0
if (select id from syscolumns where name='fTakeCountJC' and [id]=object_id('T_C_SysAccontdToDay')) is null
  ALTER TABLE T_C_SysAccontdToDay ADD fTakeCountJC INT not null default 0  
if (select id from syscolumns where name='fTakeMoneyJC' and [id]=object_id('T_C_SysAccontdToDay')) is null
  ALTER TABLE T_C_SysAccontdToDay ADD fTakeMoneyJC INT not null default 0

GO

--TABLE_EDIT_3 钱包表T_B_PurseCode增加字段 fMaxMoney 卡片上限金额

if not exists(select  * from sys.all_columns where object_id = object_id('T_B_PurseCode') and name='fUpperLimitMoney ')
   alter table T_B_PurseCode  add fUpperLimitMoney numeric(9,2) not null default 99999
go


if not exists(select  * from sys.all_columns where object_id = object_id('T_C_middle_Step1') and name='fLimitCountEnabled')
   alter table T_C_middle_Step1  add fLimitCountEnabled bit  NOT NULL DEFAULT 0
if not exists(select  * from sys.all_columns where object_id = object_id('T_C_middle_Step1') and name='fFlowType ')
   alter table T_C_middle_Step1  add fFlowType INT  NOT NULL DEFAULT 0
if not exists(select  * from sys.all_columns where object_id = object_id('T_C_middle_Step1') and name='fSourceID ')
   alter table T_C_middle_Step1  add fSourceID INT  NOT NULL DEFAULT 0  
if not exists(select  * from sys.all_columns where object_id = object_id('T_C_middle_Step1') and name='fTaskID ')
   alter table T_C_middle_Step1  add fTaskID INT   NOT NULL DEFAULT 0  
if not exists(select  * from sys.all_columns where object_id = object_id('T_C_middle_Step1') and name='fOffTranNo ')
   alter table T_C_middle_Step1  add fOffTranNo INT   NOT NULL DEFAULT 0  
if not exists(select  * from sys.all_columns where object_id = object_id('T_C_middle_Step1') and name='fPosTranNo ')
   alter table T_C_middle_Step1  add fPosTranNo INT   NOT NULL DEFAULT 0  
if not exists(select  * from sys.all_columns where object_id = object_id('T_C_middle_Step1') and name='fPosOffTranNo ')
   alter table T_C_middle_Step1  add fPosOffTranNo INT  NOT NULL DEFAULT 0  
if not exists(select  * from sys.all_columns where object_id = object_id('T_C_middle_Step1') and name='ffRecKey ')
   alter table T_C_middle_Step1  add ffRecKey VARCHAR(200)   NOT NULL DEFAULT ''  
if not exists(select  * from sys.all_columns where object_id = object_id('T_C_middle_Step1') and name='ffExternalOrder ')
   alter table T_C_middle_Step1  add ffExternalOrder VARCHAR(200)  NOT NULL DEFAULT ''  
if not exists(select  * from sys.all_columns where object_id = object_id('T_C_middle_Step1') and name='fIsRepeatWater ')
   alter table T_C_middle_Step1  add fIsRepeatWater INT  NOT NULL DEFAULT 0  
if not exists(select  * from sys.all_columns where object_id = object_id('T_C_middle_Step1') and name='fIsPendingConsRec ')
   alter table T_C_middle_Step1  add fIsPendingConsRec INT  NOT NULL DEFAULT 0  
--IF NOT EXISTS(select  * FROM SYS.all_objects WHERE name='PK_T_C_middle_Step1_primarykey_fkeyid' AND TYPE='PK')
--alter table T_C_middle_Step1 add constraint PK_T_C_middle_Step1_primarykey_fkeyid primary key(fkeyid) 
GO

--TABLE_EDIT_5 T_C_middle_Step2增加字段
if not exists(select  * from sys.all_columns where object_id = object_id('T_C_middle_Step2') and name='fLimitCountEnabled')
   alter table T_C_middle_Step2  add fLimitCountEnabled bit  NOT NULL DEFAULT 0
if not exists(select  * from sys.all_columns where object_id = object_id('T_C_middle_Step2') and name='fUserCardID ')
   alter table T_C_middle_Step2  add fUserCardID varchar(16)   NOT NULL DEFAULT ''   
if not exists(select  * from sys.all_columns where object_id = object_id('T_C_middle_Step2') and name='fStationID ')
   alter table T_C_middle_Step2  add fStationID varchar(10)   NOT NULL DEFAULT ''   
if not exists(select  * from sys.all_columns where object_id = object_id('T_C_middle_Step2') and name='fCreateTime ')
   alter table T_C_middle_Step2  add fCreateTime DATETIME   NOT NULL DEFAULT 0   
if not exists(select  * from sys.all_columns where object_id = object_id('T_C_middle_Step2') and name='fFlowType ')
   alter table T_C_middle_Step2  add fFlowType int   NOT NULL DEFAULT ''  
if not exists(select  * from sys.all_columns where object_id = object_id('T_C_middle_Step2') and name='fSourceID ')
   alter table T_C_middle_Step2  add fSourceID int   NOT NULL DEFAULT 0   
if not exists(select  * from sys.all_columns where object_id = object_id('T_C_middle_Step2') and name='fTaskID ')
   alter table T_C_middle_Step2  add fTaskID int   NOT NULL DEFAULT 0   
if not exists(select  * from sys.all_columns where object_id = object_id('T_C_middle_Step2') and name='fOffTranNo ')
   alter table T_C_middle_Step2  add fOffTranNo int   NOT NULL DEFAULT 0   
if not exists(select  * from sys.all_columns where object_id = object_id('T_C_middle_Step2') and name='fPosTranNo ')
   alter table T_C_middle_Step2  add fPosTranNo int   NOT NULL DEFAULT 0   
if not exists(select  * from sys.all_columns where object_id = object_id('T_C_middle_Step2') and name='fPosOffTranNo ')
   alter table T_C_middle_Step2  add fPosOffTranNo int   NOT NULL DEFAULT 0   
if not exists(select  * from sys.all_columns where object_id = object_id('T_C_middle_Step2') and name='ffRecKey ')
   alter table T_C_middle_Step2  add ffRecKey VARCHAR(200)   NOT NULL DEFAULT ''   
if not exists(select  * from sys.all_columns where object_id = object_id('T_C_middle_Step2') and name='ffExternalOrder ')
   alter table T_C_middle_Step2  add ffExternalOrder VARCHAR(100)   NOT NULL DEFAULT ''  
--IF NOT EXISTS(select  * FROM SYS.all_objects WHERE name='PK_T_C_middle_Step2_primarykey_fkeyid' AND TYPE='PK')
--alter table T_C_middle_Step2 add constraint PK_T_C_middle_Step2_primarykey_fkeyid primary key(fkeyid) 
GO

/*--------------------------------------------------*/
/*         TABLE_EDIT_6 T_B_Tasks增加字段           */
/*--------------------------------------------------*/
if not exists(select  * from sys.all_columns where object_id = object_id('T_B_Tasks') and name='fTaskTime')
   alter table T_B_Tasks  add fTaskTime [datetime] NOT NULL DEFAULT 0
GO

update T_B_Tasks set ftasktime = fExecTime where ftasktime = 0   
GO


--ADD_CULUM_1 汇总表T_C_SumEmp_XXXXXX增加字段fLimitConsCount、fLimitConsMoney
declare @RecCount int
declare @i int
declare @TableName varchar(17)
declare @SqlStr nvarchar(max)=''

select identity(int,1,1) id,name into #ls_Tb from sys.objects 
 where name like 'T_C_SumEmp_%' and LEN(name)=17 and type='U' 
	   
select @RecCount=COUNT(*) from #ls_Tb
if @RecCount=0 
begin
  select '没有该时间段内的数据表'
  drop table #ls_Tb
  return
end
		
set @i=1
while @i<=@RecCount
begin
  select @TableName=name from #ls_Tb where id=@i
  set @SqlStr=
      ' IF COL_LENGTH( '''+@TableName+''',''fLimitConsCount'') IS NULL  
								begin
										alter table '+@TableName+' add [fLimitConsCount] [int] NOT NULL DEFAULT ((0))  
										alter table '+@TableName+' add [fLimitConsMoney] [numeric](19, 2) NOT NULL DEFAULT ((0.00))
								end '						
    --print @sqlstr
				exec(@sqlstr)
				set @i=@i+1             
end
drop table #ls_Tb
go
--ADD_CULUM_2 汇总表T_C_ConsEmp_XXXXXX增加字段fLimitMealXXCount、fLimitMealXXMoney
declare @RecCount int
declare @i int, @j int
declare @TableName varchar(18)
declare @SqlStr nvarchar(max)=''

select identity(int,1,1) id,name into #ls_Tb from sys.objects 
 where name like 'T_C_ConsEmp_%' and type='U' 
	   
select @RecCount=COUNT(*) from #ls_Tb
if @RecCount=0 
begin
  select '没有该时间段内的数据表'
  drop table #ls_Tb
  return
end
		
set @i=1
while @i<=@RecCount
begin
  set @j=1
  select @TableName=name from #ls_Tb where id=@i
  while @j<=8
  begin
  set @SqlStr=
      ' IF COL_LENGTH( '''+@TableName+''',''fLimitMeal'+CONVERT(varchar(1),@j)+'Count'') IS NULL  
								begin
										alter table '+@TableName+' add [fLimitMeal'+CONVERT(varchar(1),@j)+'Count] [int] NOT NULL DEFAULT ((0))  
										alter table '+@TableName+' add [fLimitMeal'+CONVERT(varchar(1),@j)+'Money] [numeric](19, 2) NOT NULL DEFAULT ((0.00))
								end '						
    --print @sqlstr
				exec(@sqlstr)
		  set @j=@j+1
		end		
		set @i=@i+1             
end
drop table #ls_Tb

go
--ADD_CULUM_3 T_C_CashdataXX 增加字段fPosID
declare @RecCount int
declare @i int, @j int
declare @TableName varchar(18)
declare @SqlStr nvarchar(max)=''

select identity(int,1,1) id,name into #ls_Tb from sys.objects 
 where name like 'T_C_Cashdata%' and type='U' 
	   
select @RecCount=COUNT(*) from #ls_Tb
if @RecCount=0 
begin
  select '没有该时间段内的数据表'
  drop table #ls_Tb
  return
end
		
set @i=1
while @i<=@RecCount
begin
  set @j=1
  select @TableName=name from #ls_Tb where id=@i
  while @j<=8
  begin
  set @SqlStr=
      ' IF COL_LENGTH( '''+@TableName+''',''fPosID'') IS NULL  
								begin
										alter table '+@TableName+' add [fPosID] [int] NOT NULL DEFAULT ((0))  
								end '						
    --print @sqlstr
				exec(@sqlstr)
		  set @j=@j+1
		end		
		set @i=@i+1             
end
drop table #ls_Tb

go

--ADD_CULUM_4 设备表增加是否为转款机字段fTransPayPos

if NOT exists(select * from syscolumns where id=object_id('T_B_Pos') and name='fTransPayPos')
ALTER TABLE T_B_Pos ADD fTransPayPos int not null default 0 
GO

--ADD_CULUM_5 未确认流水表T_C_Rec_Unconfirmed增加外部订单号字段
if NOT exists(select * from syscolumns where id=object_id('T_C_Rec_Unconfirmed') and name='fExternalOrder')
   ALTER TABLE T_C_Rec_Unconfirmed add fExternalOrder varchar(100) not null default ''
GO
--VALUES_ADD_1 报表T_R_Report,T_R_Dict
insert into T_R_Report ( fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fRemark) values 
	( 1, '考勤日报表' , 'UP_Report_Atd_Days' , 0, '001' , '' , 1, 0, 1, '' , 0, '' , null , '考勤日报表查询' ) 
insert into T_R_Report ( fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fRemark) values 
	( 2, '考勤流水表' , 'UP_Report_Atd_CardRecordN' , 0, '001' , '' , 1, 0, null , '' , 0, '' , null , '考勤流水表' ) 
insert into T_R_Report ( fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fRemark) values 
	( 3, '考勤月报表' , 'UP_Report_Atd_Months' , 0, '001' , '' , 1, 0, null , '' , 0, '' , null , '考勤月报表查询' ) 
insert into T_R_Report ( fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fRemark) values 
	( 4, '门禁流水记录表' , 'UP_Report_Egs_CardRecordN' , 1, '003' , '' , 1, null , null , '' , null , '' , null , '门禁流水记录表' ) 
insert into T_R_Report ( fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fRemark) values 
	( 5, '门禁设备错误日志' , 'UP_Report_Egs_ErrorRecord' , 1, '003' , '' , 1, null , null , '' , null , '' , null , '查看门禁控制器设备返回的错误日志记录' ) 
insert into T_R_Report ( fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fRemark) values 
	( 6, '出纳日报表' , 'UP_Report_Cns_Total_CashDays' , 2, '002002' , 'CashierDay.fr3' , 4, 2 , 1, '' , null , 'S1|S2|S3|S4|S5|S6|S7|S8|S9|S10|S11|S12|S13|S14|S15|S16|S17|S18|S19|S20|S21|S22|S23|S24|S25|S26|S27|S28|S29|S30|S31|S32|S33|S34|S35|S36|S37|S38|S39|S40|S41|S42|S43|S44|S45|S46|S47|S48|S49' , null , '上缴金额 = 开户金额 + 开户押金 + 开户卡费 + 开户管理费 + 撤户手续费 - 撤户金额 - 应退押金 + 存款金额 + 存款管理费 + (-取款金额)' ) 
insert into T_R_Report ( fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fRemark) values 
	( 7, '出纳月报表' , 'UP_Report_Cns_Total_CashMonth' , 2, '002002' , 'CashierMonth.fr3' , 4, 2 , 1, '' , null , 'S1|S2|S3|S4|S5|S6|S7|S8|S9|S10|S11|S12|S13|S14|S15|S16|S17|S18|S19|S20|S21|S22|S23|S24|S25|S26|S27|S28|S29|S30|S31|S32|S33|S34|S35|S36|S37|S38|S39|S40|S41|S42|S43|S44|S45|S46|S47|S48|S49' , null , '上缴金额 = 开户金额 + 开户押金 + 开户卡费 + 开户管理费 + 撤户手续费 - 撤户金额 - 应退押金 + 存款金额 + 存款管理费 + (-取款金额)' ) 
insert into T_R_Report ( fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fRemark) values 
	( 8, '出纳阶段报表' , 'UP_Report_Cns_Total_CashStaged' , 2, '002002' , 'CashierSpace.fr3' , 4, 2 , 1, '' , null , 'S1|S2|S3|S4|S5|S6|S7|S8|S9|S10|S11|S12|S13|S14|S15|S16|S17|S18|S19|S20|S21|S22|S23|S24|S25|S26|S27|S28|S29|S30|S31|S32|S33|S34|S35|S36|S37|S38|S39|S40|S41|S42|S43|S44|S45|S46|S47|S48|S49' , null , '上缴金额 = 开户金额 + 开户押金 + 开户卡费 + 开户管理费 + 撤户手续费 - 撤户金额 - 应退押金 + 存款金额 + 存款管理费 + (-取款金额)' ) 
insert into T_R_Report ( fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fRemark) values 
	( 9, '账户结余表' , 'UP_Report_Cns_AccountBalance' , 2, '002004' , '' , 4, 1, 1, '' , null , 'S6|S7|S8|S9|S10|S11|S12|S13|S14|S15|S16|S17|S18|S19|S20|S21|S22|S23|S24|S25' , null , '账户结余表' ) 
insert into T_R_Report ( fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fRemark) values 
	( 10, '消费汇总表' , 'UP_Report_Cns_Total_MealStation' , 2, '002004' , '' , 1, null , null , '' , null , 'S3|S4|S5|S6|S7|S8|S9|S10|S11|S12|S13|S14|S15|S16|S17|S18|S19|S20' , null , '消费汇总表' ) 
insert into T_R_Report ( fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fRemark) values 
	( 11, '营业报表(日)' , 'UP_Report_Cns_ConsDay' , 2, '002001' , 'ConsDay.fr3' , 3, 2, null , '' , null , 'S5|S6|S7|S8|S9|S10' , null , '营业报表(日)' ) 
insert into T_R_Report ( fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fRemark) values 
	( 12, '营业报表(月)' , 'UP_Report_Cns_ConsMonth' , 2, '002001' , 'ConsMonth.fr3' , 3, 2, null , '' , null , 'S5|S6|S7|S8|S9|S10' , null , '营业报表(月)' ) 
insert into T_R_Report ( fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fRemark) values 
	( 13, '营业阶段报表' , 'UP_Report_Cns_ConsSpace' , 2, '002001' , 'ConsSpace.fr3' , 3, 2, null , '' , null , 'S5|S6|S7|S8|S9|S10' , null , '营业阶段报表' ) 
insert into T_R_Report ( fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fRemark) values 
	( 14, '操作人员日志' , 'UP_Report_detail_OperatorLog' , 2, '002004' , '' , 3, null , null , '' , null , '' , null , '' ) 
insert into T_R_Report ( fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fRemark) values 
	( 15, '部门消费情况表' , 'UP_Report_Cns_Detail_DeptMeal' , 2, '002001' , '' , 1, null , null , '' , null , 'S2|S3|S4|S5|S6|S7' , null , '' ) 
insert into T_R_Report ( fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fRemark) values 
	( 16, '餐次日报表' , 'UP_Report_Cns_Total_MealDays' , 2, '002001' , '' , 1, null , 1, '' , null , 'S1|S2|S3|A4|S5|S6|S7|A8|S9|S10|S11|A12|S13|S14|S15|A16|S17|S18|S19|A20' , null , '' ) 

insert into T_R_Report ( fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fBPageDis, fRemark) values 
	( 17, '流水记录表' , 'UP_Report_Cns_RecordN' , 2, '002003' , '' , 0, 0, 1, '' , 5, '' , null , 1, '' ) 
insert into T_R_Report ( fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fRemark) values 
	( 18, '账户查询' , 'UP_Report_Cns_Account' , 2, '004' , '' , 0, 0, null , '' , 0, '' , null , '[状态]:账户状态；   [交易号]:卡交易流水号(写卡自增)' ) 

insert into T_R_Report ( fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fRemark) values 
	( 19, '人员权限' , 'UP_Report_EGS_EmpCurrRule' , 1, '003' , '' , 1, null , null , '' , null , '' , null , '查看人员权限' )
insert into T_R_Report ( fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fRemark) values 
	( 20, '权限变更记录' , 'UP_Report_EGS_EmpRuleHistory' , 1, '003' , '' , 1, null , null , '' , null , '' , null , '门禁权限变更历史记录查询' ) 

insert into T_R_Report ( fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fRemark) values 
	( 21, '补助领取报表' , 'UP_Report_sub_detail_AlreadySubsidy' , 2, '002004' , '' , 3, 2 , null , '' , null , 'S4' , null , '补助领取报表' ) 	
insert into T_R_Report ( fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fRemark) values 
	( 22, '账户结余汇总表' , 'UP_Report_SysAccount' , 2, '002002' , '' , 2, 2 , 1 , '' , 0 , '' , null , '现账户余额=原账户余额-营业金额+开户金额-撤户金额+存款金额-取款金额-挂失手续费-解挂手续费-换卡手续费-补卡卡费-补卡手续费+纠错金额+补助金额-补助清零金额+圈存金额+圈存补款金额' ) 	
insert into T_R_Report ( fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fRemark) values 
	( 23, '出纳阶段报表（按钱包）' , 'UP_Report_Cns_Total_CashStagedByPurse' , 2, '002002' , 'CashierSpaceByPurse.fr3' , 4, 2 , 1 , NULL , NULL , 'S1|S2|S3|S4|S5|S6|S7|S8|S9|S10|S11|S12|S13|S14|S15|S16|S17|S18|S19|S20|S21|S22|S23|S24|S25|S26|S27|S28|S29|S30|S31|S32|S33|S34|S35|S36|S37|S38|S39|S40|S41|S42|S43|S44|S45|S46|S47|S48|S49' , null , '账户结余汇总表' ) 	
insert T_R_Report(fReportID,fReportName,fReportProc,fReportType,fGroupID,ffr3fileName,fDisPlay,fDefaultDis,fPrintDirection,fColUnDis,fColFix,fTotleDis,fHide,fRemark)values
 (24,'身份消费统计报表','UP_Report_Cns_Total_ManTypeMeal',2,'002001',NULL,1,0,NULL,NULL,0,'S3|S4|S5|S6|S7|S8|S9|S10|S11',NULL,'按身份餐次进行消费统计')
INSERT INTO T_R_Report (fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fRemark) VALUES 
	(25, '营业组分组报表', 'UP_Report_Cns_Total_DeptBZ', 2, '002001', '', 1, null, null, null, null, 'S1|S2|S3|S4|S5|S6|S7|S8|S9|S10|S11|S12|S13|S14|S15|S16|S17|S18|S19|S20|S21|S22|S23|S24|S25|S26|S27|S28|S29|S30', null,'')
insert into T_R_Report ( fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fRemark) values 
	( 26, '菜品消费汇总报表' , 'UP_Report_Cns_DishRecSum' , 2, '002004' , '' , 1, null , 1, '' , null , 'S3|S4|S5' , null , '菜品消费汇总报表' )
insert into T_R_Report ( fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fRemark) values 
	( 27, '菜品消费明细报表' , 'UP_Report_Cns_DishRecDetail' , 2, '002003' , '' , 0, 0 , 1 , '' , 5 , '' , null , '' ) 

insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 9, 'EmpSelect' , 1, '人员选择' , 0, 'Select * From T_B_Dept|T_B_Dept|fDeptCode|fDeptName' , '' , '' , '' , '' , null , 1, null , 1, '请选择要查询的人员' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'timeBegin' , 2, '查询日期起' , 0, '' , '' , '2099-01-01' , '2000-01-01' , 'today' , null , 1, null , 1, '查询报表的起始日期' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'timeEnd' , 3, '查询日期止' , 0, '' , '' , '2099-01-01' , '2000-01-01' , 'today' , null , 1, null , 1, '查询报表的结束时间' )
	
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 9, 'EmpSelect' , 1, '人员选择' , 0, '' , '' , '' , '' , '' , null , 1, null , 2, '请选择要查询打卡流水的人员' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 8, 'RecType' , 2, '记录类型选择' , 0, 'Select * From T_A_RecType|T_A_RecType|fTypeID|fTypeName' , '' , '' , '' , '0' , null , 1, null , 2, '请选择查询流水的类型' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 2, 'DateBegin' , 3, '查询时间起' , 0, '' , '' , '2099-12-01' , '2000-01-01' , 'ToDay' , null , 1, null , 2, '请设置流水查询起始时间' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 2, 'DateEnd' , 4, '查询时间止' , 0, '' , '' , '2099-12-01' , '2000-01-01' , 'ToDay' , null , 1, null , 2, '请设置流水查询结束时间' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 8, 'PosID' , 5, '设备选择' , 0, 'Select * From V_B_AtdPos|V_B_AtdPos|fPosID|fPosID|fPosName' , '' , '' , '' , '' , null , 1, null , 2, '请选择要查询的考勤设备' ) 
	
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 9, 'fEmpSelect' , 1, '设置人员' , 0, '' , '' , '' , '' , '' , null , 1, null , 3, '请选择要查询月报表的人员' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 4, 'fYear' , 2, '年份' , 0, '' , '' , '2099' , '1990' , 'toyear' , null , 1, null , 3, '请设置统计月报表的年份' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 4, 'fMonth' , 3, '月份' , 0, '' , '' , '12' , '1' , '4' , null , 1, null , 3, '请设置统计月报表的月份' ) 
	
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 9, 'EmpSelect' , 1, '查询人员选择' , 0, '' , '' , '' , '' , '' , null , 1, null , 4, '请选择要查询门禁流水的人员' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 8, 'RecType' , 2, '记录类型' , 0, 'Select * From T_E_RecType|T_E_RecType|fTypeID|fTypeName' , '' , '' , '' , '0' , null , 1, null , 4, '请设置要查询的门禁记录类型' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 2, 'BeginDate' , 3, '开始日期' , 0, '' , '' , '2099-12-31' , '2000-01-01' , 'ToDay' , null , 1, null , 4, '查询开始日期' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 2, 'EndDate' , 4, '结束日期' , 0, '' , '' , '2099-12-31' , '2000-01-01' , 'ToDay' , null , 1, null , 4, '查询结束日期' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 8, 'PosID' , 5, '查询设备选择' , 0, 'Select * From V_B_EgsPos|V_B_EgsPos|fPosID|fPosID|fPosName' , '' , '' , '' , '' , null , 1, null , 4, '请选择要查询的门禁控制器' )
			
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 8, 'ErrorCode' , 1, '选择错误类型' , 0, 'Select * From T_E_ErrType|T_E_ErrType|fTypeID|fTypeName' , '' , '' , '' , '0' , null , 1, null , 5, '请选择要查询的门禁错误记录类型' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 2, 'BeginDate' , 2, '开始时间' , 0, '' , '' , '2099-12-31' , '2000-01-01' , 'ToDay' , null , 1, null , 5, '请设置查询记录的开始时间' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 2, 'EndDate' , 3, '结束时间' , 0, '' , '' , '2099-12-31' , '2000-01-01' , 'ToDay' , null , 1, null , 5, '请设置查询记录的结束时间' ) 

insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
    ( 11, 'a.foperid' , 1, '操作员' , 1, 'Select * From T_B_Manager|T_B_Manager|fOperID|fOperName' , '' , '' , '' , '' , 1, 1, null , 6, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
    ( 2, 'fdatetime' , 2, '查询日期' , 1, '' , '' , '2099-01-01' , '1900-01-01' , 'Today' , 1, 1, null , 6, '查询日期' ) 

insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 11, 'a.foperid' , 1, '操作员' , 1, 'Select * From T_B_Manager|T_B_Manager|fOperID|fOperName' , '' , '' , '' , '' , 1, 1, null , 7, '操作员列表' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 4, 'fyear' , 2, '查询年份' , 1, '' , '' , '2099' , '1900' , 'TOYEAR' , 1, 1, null , 7, '查询年份' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 4, 'fmonth' , 3, '查询月份' , 1, '' , '' , '12' , '1' , 'ToMonth' , 1, 1, null , 7, '查询月份' )   
    
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 11, 'a.foperid' , 1, '操作员' , 1, 'Select * From T_B_Manager|T_B_Manager|fOperID|fOperName' , '' , '' , '' , '' , 1, 1, null , 8, '多选操作员' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'fBegin' , 2, '查询开始日期' , 1, '' , '' , '2099-01-01' , '2000-01-01' , 'Today' , 1, 1, null , 8, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'fEnd' , 3, '查询结束日期' , 1, '' , '' , '2099-01-01' , '2000-01-01' , 'Today' , 1, 1, null , 8, '' )   

	
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'fBegin' , 1, '查询开始日期' , 0, '' , '' , '2099-01-01' , '2000-01-01' , 'Today' , 1, 1, null , 9, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 10, 'fDept' , 2, '部门' , 0, '' , '' , '' , '' , '' , null , 1, null , 9, '' ) 
	
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'fBegin' , 1, '查询开始日期' , 0, '' , '' , '2099-01-01' , '2000-01-01' , 'Today' , 1, 1, null , 10, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'fEnd' , 2, '查询结束日期' , 0, '' , '' , '2099-01-01' , '2000-01-01' , 'Today' , 1, 1, null , 10, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 6, 'fType' , 3, '查询方式' , 0, '按机号统计|按部门统计|按人员统计' , '' , '' , '' , '0' , 1, 1, null , 10, '' )  
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
    ( 11, 'R.fPurseID' , 4, '钱包选择' , 1, 'select  * from T_B_PurseCode|T_B_PurseCode|fPurseCode|fPurseName' , '' , '' , '' , '' , null, 1, null , 10, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
    ( 6, 'PurseSum' , 5, '钱包统计方式' , 0, '按钱包单独统计|按钱包汇总统计' , '' , '' , '' , '0' , 1, 1, null , 10, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
    ( 13, 'd.fDeptCode' , 6, '部门选择' , 0, '' , '' , '' , '' , '' , null, 1, null , 10, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
    ( 9, 'EmpSelect' , 7, '人员选择' , 0, '' , '' , '' , '' , '' , null, 1, null , 10, '' ) 

insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
    ( 11, 'R.fPosID' , 8, '设备选择' , 0, 'Select * From V_B_SitePos where fPosType=1|V_B_SitePos|fPosID|fPosID|fPosName' , '' , '' , '' , '' , null, 1, null , 10, '请选择要查询的消费机' ) 
        	
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'fDate' , 1, '查询日期' , 0, '' , '' , '2099-01-01' , '2000-01-01' , 'Today' , 1, 1, null , 11, '' ) 
INSERT INTO [dbo].[T_R_Dict] ([fDictType],[fDictName],[fSerialNO],[fDisplayName],[fFootType],[fDictContent],[fMask],[fMax],[fMin],[fDictDefault],[fIsCheck],[fIsPrint],[fIsScript],[fReportID],[fRemark])VALUES
(11,'A.fSt_id ',2,'营业组',0,'Select * From T_B_Stbm|T_B_Stbm|fSt_Id|fSt_Id|fSt_Name',NULL,'','',NULL,null,1,NULL,11, '请选择要查询的营业组')

INSERT INTO [dbo].[T_R_Dict] ([fDictType],[fDictName],[fSerialNO],[fDisplayName],[fFootType],[fDictContent],[fMask],[fMax],[fMin],[fDictDefault],[fIsCheck],[fIsPrint],[fIsScript],[fReportID],[fRemark])VALUES
(11,'A.fBz_id ',3,'班组',0,'Select * From T_B_Bzbm|T_B_Bzbm|fBz_Id|fBz_Id|fBz_Name',NULL,'','',NULL,null,1,NULL,11, '请选择要查询的班组')
	
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 4, 'Year' , 1, '年' , 0, '' , '' , '2050' , '2000' , 'toYear' , 1, 1, null , 12, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 4, 'Month' , 2, '月' , 0, '' , '' , '12' , '1' , 'toMonth' , 1, 1, null , 12, '' ) 
INSERT INTO [dbo].[T_R_Dict] ([fDictType],[fDictName],[fSerialNO],[fDisplayName],[fFootType],[fDictContent],[fMask],[fMax],[fMin],[fDictDefault],[fIsCheck],[fIsPrint],[fIsScript],[fReportID],[fRemark])VALUES
	(11,'A.fSt_id ',3,'营业组',0,'Select * From T_B_Stbm|T_B_Stbm|fSt_Id|fSt_Id|fSt_Name',NULL,'','',NULL,null,1,NULL,12, '请选择要查询的营业组')
	
INSERT INTO [dbo].[T_R_Dict] ([fDictType],[fDictName],[fSerialNO],[fDisplayName],[fFootType],[fDictContent],[fMask],[fMax],[fMin],[fDictDefault],[fIsCheck],[fIsPrint],[fIsScript],[fReportID],[fRemark])VALUES
	(11,'A.fBz_id ',4,'班组',0,'Select * From T_B_Bzbm|T_B_Bzbm|fBz_Id|fBz_Id|fBz_Name',NULL,'','',NULL,null,1,NULL,12, '请选择要查询的班组')
		
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'fBeginDate' , 1, '开始日期' , 0, '' , '' , '2099-01-01' , '2000-01-01' , '' , 1, 1, null , 13, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'fEndDate' , 2, '结束日期' , 0, '' , '' , '2099-01-01' , '2000-01-01' , '' , 1, 1, null , 13, '' )   
INSERT INTO [dbo].[T_R_Dict] ([fDictType],[fDictName],[fSerialNO],[fDisplayName],[fFootType],[fDictContent],[fMask],[fMax],[fMin],[fDictDefault],[fIsCheck],[fIsPrint],[fIsScript],[fReportID],[fRemark])VALUES
(11,'A.fSt_id ',3,'营业组',0,'Select * From T_B_Stbm|T_B_Stbm|fSt_Id|fSt_Id|fSt_Name',NULL,'','',NULL,null,1,NULL,13, '请选择要查询的营业组')

INSERT INTO [dbo].[T_R_Dict] ([fDictType],[fDictName],[fSerialNO],[fDisplayName],[fFootType],[fDictContent],[fMask],[fMax],[fMin],[fDictDefault],[fIsCheck],[fIsPrint],[fIsScript],[fReportID],[fRemark])VALUES
(11,'A.fBz_id ',4,'班组',0,'Select * From T_B_Bzbm|T_B_Bzbm|fBz_Id|fBz_Id|fBz_Name',NULL,'','',NULL,null,1,NULL,13, '请选择要查询的班组') 
	
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'fBegDateTime' , 1, '开始日期' , 0, '' , '' , '2099-01-01' , '2000-01-01' , '' , 1, 1, null , 14, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'fEndDateTime' , 2, '结束日期' , 0, '' , '' , '2099-01-01' , '2000-01-01' , '' , 1, 1, null , 14, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 8, 'fOperID' , 3, '操作员编码' , 0, 'Select * From T_B_Manager|T_B_Manager|fOperID|fOperID|fOperName' , '' , '' , '' , '' , null , 1, null , 14, '' ) 	
	
	
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'fBegDateTime' , 1, '开始日期' , 0, '' , '' , '2099-01-01' , '2000-01-01' , '' , 1, 1, null , 15, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'fEndDateTime' , 2, '结束日期' , 0, '' , '' , '2099-01-01' , '2000-01-01' , '' , 1, 1, null , 15, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 13, 'R.fDeptCode' , 3, '部门编号' , 0, '' , '' , '' , '' , '' , null , 1, null , 15 ,'' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
    ( 6, 'TotalOrDetail' , 4, '钱包统计方式' , 0, '消费明细|消费汇总' , '' , '' , '' , '0' , 1, 1, null , 15, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
    ( 6, 'PurseSum' , 5, '钱包统计方式' , 0, '按钱包单独统计|按钱包汇总统计' , '' , '' , '' , '0' , 1, 1, null , 15, '' )     	
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'fBegDateTime' , 1, '开始日期' , 0, '' , '' , '2099-01-01' , '2000-01-01' , '' , 1, 1, null , 16, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'fEndDateTime' , 2, '结束日期' , 0, '' , '' , '2099-01-01' , '2000-01-01' , '' , 1, 1, null , 16, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 8, 'posname' , 3, '终端机名称' , 0, 'Select * From T_B_Pos where fPosType = 1 |T_B_Pos|fPosID|fPosID|fPosName' , '' , '' , '' , '' , null , null , null , 16, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 8, 'bzname' , 4, '班组名称' , 0, 'Select * From T_B_Bzbm|T_B_Bzbm|fBz_Id|fBz_Id|fBz_Name' , '' , '' , '' , '' , null , null , null , 16, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
    ( 8, 'St_Name' ,5, '营业组' , 0, 'Select * From T_B_Stbm|T_B_Stbm|fSt_Id|fSt_Id|fSt_Name' , '' , '' , '' , '0' , 0, 1, null , 16, '' ) 	

insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 9, 'strWhere' , 1, '人员' , 0, '' , '' , '' , '' , '' , null , 1, null , 17, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 8, 'ConsState' , 2, '事件类型' , 0, 'Select * From T_C_ConsState|T_C_ConsState|fStateID|fStateID|fStateName' , '' , '' , '' , '99' , 1, 1, null , 17, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'BeginDate' , 3, '开始日期' , 1, '' , '' , '2099-01-01' , '2000-01-01' , 'today' , 1, 1, null , 17, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 1, 'BeginTime' , 4, '开始时间' , 1, '' , '' , '23:59:59' , '00:00:01' , '00:00:00' , 1, 1, null , 17, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'EndDate' , 5, '结束日期' , 1, '' , '' , '2099-01-01' , '2000-01-01' , 'today' , 1, 1, null , 17, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 1, 'EndTime' , 6, '结束时间' , 0, '' , '' , '23:59:59' , '00:00:01' , '23:59:59' , 1, 1, null , 17, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 8, 'PosID' , 7, 'POS机' , 0, 'Select * From T_B_Pos|T_B_Pos|fPosID|fPosID|fPosName' , '' , '' , '' , '' , null , 1, null , 17, '' ) 
	
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 9, 'fEmpNo' , 1, '人员选择' , 0, '' , '' , '' , '' , '' , null , 1 , null , 18, '' ) 
		    
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 9, 'EmpSelect' , 1, '人员选择' , 0, 'Select * From T_B_Dept|T_B_Dept|fDeptCode|fDeptName' , '' , '' , '' , '' , null , 1, null , 19, '请选择要查询的人员' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 8, 'PosID' , 2, 'POS机' , 0, 'Select * From T_B_Pos where fPosType=2|T_B_Pos|fPosID|fPosID|fPosName' , '' , '' , '' , '' , null , 1, null , 19, '请选择要查询的设备' ) 
	
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 9, 'EmpSelect' , 1, '人员选择' , 0, 'Select * From T_B_Dept|T_B_Dept|fDeptCode|fDeptName' , '' , '' , '' , '' , null , 1, null , 20, '请选择要查询的人员' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'timeBegin' , 2, '查询日期起' , 0, '' , '' , '2099-01-01' , '2000-01-01' , 'today' , null , 1, null , 20, '查询报表的起始日期' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'timeEnd' , 3, '查询日期止' , 0, '' , '' , '2099-01-01' , '2000-01-01' , 'today' , null , 1, null , 20, '查询报表的结束时间' ) 

insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 9, 'EmpSelect' , 1, '人员选择' , 0, 'Select * From T_B_Dept|T_B_Dept|fDeptCode|fDeptName' , '' , '' , '' , '' , null , 1, null , 21, '请选择要查询的人员' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'timeBegin' , 2, '查询日期起' , 0, '' , '' , '2099-01-01' , '2000-01-01' , 'today' , null , 1, null , 21, '查询报表的起始日期' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'timeEnd' , 3, '查询日期止' , 0, '' , '' , '2099-01-01' , '2000-01-01' , 'today' , null , 1, null , 21, '查询报表的结束时间' ) 

insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'timeBegin' , 1, '查询日期起' , 0, '' , '' , '2099-01-01' , '2000-01-01' , 'today' , null , 1, null , 22, '查询报表的起始日期' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'timeEnd' , 2, '查询日期止' , 0, '' , '' , '2099-01-01' , '2000-01-01' , 'today' , null , 1, null , 22, '查询报表的结束时间' ) 
	
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 11, 'a.foperid' , 1, '操作员' , 1, 'Select * From T_B_Manager|T_B_Manager|fOperID|fOperName' , '' , '' , '' , '' , 1 , 1, null , 23, '多选操作员' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'fBeginDate' , 2, '开始日期' , 0, '' , '' , '2099-01-01' , '2000-01-01' , '' , 1 , 1, null , 23, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'fEndDate' , 3, '结束日期' , 0, '' , '' , '2099-01-01' , '2000-01-01' , '' , 1 , 1, null , 23, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 11, 'a.fAppID' , 4, '钱包选择' , 1, 'select  * from T_B_PurseCode|T_B_PurseCode|fPurseCode|fPurseName' , '' , '' , '' , '' , 0 , 1, null , 23, '' ) 
	
insert T_R_Dict(fDictType,fDictName,fSerialNO,fDisplayName,fFootType,fDictContent,fMask,fMax,fMin,fDictDefault,fIsCheck,fIsPrint,fIsScript,fReportID,fRemark)values
  (2,'BeginTime',1,'查询时间起',0,NULL,NULL,'2099-12-01','2000-01-01','ToDay',NULL,1,NULL,24,'请设置查询起始时间')
insert T_R_Dict(fDictType,fDictName,fSerialNO,fDisplayName,fFootType,fDictContent,fMask,fMax,fMin,fDictDefault,fIsCheck,fIsPrint,fIsScript,fReportID,fRemark)values
  (2,'EndTime',2,'查询时间止',0,NULL,NULL,'2099-12-01','2000-01-01','ToDay',NULL,1,NULL,24,'请设置查询结束时间')
insert T_R_Dict(fDictType,fDictName,fSerialNO,fDisplayName,fFootType,fDictContent,fMask,fMax,fMin,fDictDefault,fIsCheck,fIsPrint,fIsScript,fReportID,fRemark)values
 (11,'E.fId_TypeId',3,'身份类型',0,'Select * From T_B_ManType|T_B_ManType|fId_TypeId|fId_TypeId|fId_TypeName',NULL,NULL,NULL,NULL,NULL,1,NULL,24,'请选择身份类型')
insert T_R_Dict(fDictType,fDictName,fSerialNO,fDisplayName,fFootType,fDictContent,fMask,fMax,fMin,fDictDefault,fIsCheck,fIsPrint,fIsScript,fReportID,fRemark)values
  (11,'R.fMealID',4,'餐次',0,'Select * From T_B_MealSet|T_B_MealSet|fMeal_Id|fMeal_Id|fMeal_Name',NULL,NULL,NULL,NULL,NULL,1,NULL,24,'请选择餐次类型')    
insert T_R_Dict(fDictType,fDictName,fSerialNO,fDisplayName,fFootType,fDictContent,fMask,fMax,fMin,fDictDefault,fIsCheck,fIsPrint,fIsScript,fReportID,fRemark)values
  (11,'R.fPosID',5,'设备选择',0,'Select * From V_B_SitePos where fPosType=1|V_B_SitePos|fPosID|fPosID|fPosName',NULL,NULL,NULL,NULL,NULL,1,NULL,24,'请选择要查询的消费机')
	INSERT INTO T_R_Dict (fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) VALUES 
	(0, 'fEndDateTime', 1, '开始日期', 0, '', '', '2099-01-01', '2000-01-01', '', null, 1, null, 25, '')
	INSERT INTO T_R_Dict (fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) VALUES 
	(0, 'fBegDateTime', 2, '结束日期', 0, '', '', '2099-01-01', '2000-01-01', '', 1, 1, null, 25, '')
	INSERT INTO T_R_Dict (fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) VALUES 
	(11, 'b.fBz_id', 3, '营业组', 0, 'Select * From T_B_Bzbm|T_B_Bzbm|fBz_Id|fBz_Id|fBz_Name', null, null, null, null, null, 1, null, 25, '营业组')
	INSERT INTO T_R_Dict (fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) VALUES 
	(11, 'R.fPurseID', 4, '钱包选择', 1, 'select  * from T_B_PurseCode|T_B_PurseCode|fPurseCode|fPurseName', '', '', '', '', null, 1, null, 25, '')

		insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
			( 0, 'fBegDateTime' , 1, '开始日期' , 0, '' , '' , '2099-01-01' , '2000-01-01' , '' , 1, 1, null , 26, '' ) 
		insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
			( 0, 'fEndDateTime' , 2, '结束日期' , 0, '' , '' , '2099-01-01' , '2000-01-01' , '' , 1, 1, null , 26, '' ) 
		insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
			( 11, 'H.fDishID' , 3, '菜品名称' , 0, 'Select * From T_B_Dish|T_B_Dish|fDishID|fDishID|fDishName' , '' , '' , '' , '' , null , null , null , 26, '' ) 
		insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
			( 11, 'D.fbz_id' , 4, '班组名称' , 0, 'Select * From T_B_Bzbm|T_B_Bzbm|fBz_Id|fBz_Id|fBz_Name' , '' , '' , '' , '' , null , null , null , 26, '' ) 
			
	insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'fBegDateTime' , 1, '开始日期' , 0, '' , '' , '2099-01-01' , '2000-01-01' , '' , 1, 1, null , 27, '' ) 
insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
	( 0, 'fEndDateTime' , 2, '结束日期' , 0, '' , '' , '2099-01-01' , '2000-01-01' , '' , 1, 1, null , 27, '' ) 
		insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
			( 11, 'b.fDishID' , 3, '菜品名称' , 0, 'Select * From T_B_Dish|T_B_Dish|fDishID|fDishID|fDishName' , '' , '' , '' , '' , null , null , null , 27, '' ) 
		insert into T_R_Dict ( fDictType, fDictName, fSerialNO, fDisplayName, fFootType, fDictContent, fMask, fMax, fMin, fDictDefault, fIsCheck, fIsPrint, fIsScript, fReportID, fRemark) values 
			( 11, 'D.fbz_id' , 4, '班组名称' , 0, 'Select * From T_B_Bzbm|T_B_Bzbm|fBz_Id|fBz_Id|fBz_Name' , '' , '' , '' , '' , null , null , null , 27, '' ) 

--VIEW_EDIT_1 修改视图V_B_Employee

IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[V_B_Employee]'))
DROP VIEW [dbo].[V_B_Employee]
GO
CREATE view [dbo].[V_B_Employee] as  
SELECT 	T_B_Employee.fAccountID,
	T_B_Employee.fEmployeeCode,
	T_B_Employee.fSerialNo,
	T_B_Employee.fCardID,
	T_B_Employee.fName,
	T_B_Employee.fIDCard,
	T_B_Employee.fSex,
	T_B_Employee.fBirthday,
	T_B_Employee.fNation,
	T_B_Employee.fNativePlace,
	T_B_Employee.fDept,
	T_B_Employee.fRoomID,
	T_B_Employee.fJob,
	T_B_Employee.fPhoto,
	T_B_Employee.fChecked,
	T_B_Employee.fCheckSystem,
	T_B_Employee.fDiploma,
	T_B_Employee.fGraduateDate,
	T_B_Employee.fSchool,
	T_B_Employee.fSpecialty,
	T_B_Employee.fAddress,
	T_B_Employee.fPhoneCode,
	T_B_Employee.fMobilePhoneCode,
	T_B_Employee.fEmail,
	T_B_Employee.fEnterDate,
	T_B_Employee.fCheckDate,
	T_B_Employee.fState,
	T_B_Employee.fResume,
	T_B_Employee.fRemark,
	T_B_Employee.fCard_State,
	T_B_Employee.fPassword,
	T_B_Employee.fCard_TypeId,
	T_B_Employee.fPass_True,
	T_B_Employee.fId_TypeId,
	T_B_Employee.fKh_Date,
	T_B_Employee.fKh_Money,
	T_B_Employee.fKh_JE,
	T_B_Employee.fKh_Charge,
	T_B_Employee.fBalanceMon,
	T_B_Employee.fBalanceSub,
	T_B_Employee.fCountMon,
	T_B_Employee.fCountSub,
	T_B_Employee.fXgEnable,
	T_B_Employee.fEgsPass,
	T_B_Employee.fCardValidDate,
	T_B_Employee.fIsBind,
	T_B_Employee.fBankNo,
	T_B_Employee.fParentName,
	T_B_Employee.fLastOperateTime,
	T_B_Employee.fHaveKhWater,
	T_B_Employee.rver,
	T_B_Dept.fDeptName, T_B_ManType.fId_TypeName,T_B_ManType.fcons_Group AS fGroup,   
      T_B_ManType.fsubsity_money, T_B_ViceCards.fViceCard1,T_B_ViceCards.fViceCard2,T_B_ViceCards.fViceCard3,T_B_ViceCards.fViceCard4  
FROM T_B_Employee LEFT OUTER JOIN T_B_ManType ON  T_B_Employee.fId_TypeId = dbo.T_B_ManType.fId_TypeID   
      LEFT OUTER JOIN T_B_Dept ON dbo.T_B_Employee.fDept = dbo.T_B_Dept.fDeptCode   
      Left Outer Join (select fAccountID,  
      Max(case num when 1 then fPhysicalNo end) as fViceCard1,  
      Max(case num when 2 then fPhysicalNo end) as fViceCard2,  
      Max(case num when 3 then fPhysicalNo end) as fViceCard3,  
      Max(case num when 4 then fPhysicalNo end) as fViceCard4 from   
     (select (select count(1) from T_B_CardInfo where fAccountID=t.fAccountID and fKeyID<=t.fKeyID) as num ,t.fAccountID,t.fPhysicalNo from T_B_CardInfo t where t.fCard_State = 0 ) as b Group by fAccountID)   
     as T_B_ViceCards on T_B_Employee.fAccountID = T_B_ViceCards.fAccountID  
go

sp_refreshview V_B_Employee
go
 

--VIEW_EDIT_2 修改视图V_B_pos
IF EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[V_B_Pos]') AND OBJECTPROPERTY(id, N'IsView') = 1) 
drop view V_B_Pos
GO 
CREATE VIEW  [V_B_Pos]  
AS  
SELECT    P.fTransPayPos, P.fPosID, P.fPosName, P.fPosType, P.fPosClass, P.fPosPwd, P.fCom, P.fConnType, P.fState, P.fSiteID, P.fIpAddr, P.fTcpPort, P.fServerIp, P.fIssuer, P.fPosVersion,   
                      P.fMJType, P.fDoorLock, P.fWarnTime, P.fFireAlarmTime, P.fHintTime, P.fWarnExport, P.fFireWarnExport, P.fSuperPsd, P.fBasePsd, P.fIntimidatePwd,   
                      P.fFireWarnOpen, P.fWarnOpen, P.fRecDisposal, P.fSN, P.fIpMask, P.fGetWay, P.fServerMac, P.fGetWayMac, P.fPosMac, P.fConsGroup, P.fRate, P.fTimeUnit,   
                      PT.fPosTypeName, ISNULL(PR.fRecDate, CONVERT(varchar(10), GETDATE(), 120)) AS fRecDate, ISNULL(PR.fRecCount, 0) AS fRecCount, ISNULL(PR.fConsSum, 0)   
                      AS fConsSum, ISNULL(PR.fSaveCount, 0) AS fSaveCount, ISNULL(PR.fSaveSum, 0) AS fSaveSum, ISNULL(PR.fTakeCount, 0) AS fTakeCount, ISNULL(PR.fTakeSum, 0)   
                      AS fTakeSum, ISNULL(PR.fPutRightCount, 0) AS fPutRightCount, ISNULL(PR.fPutRightSum, 0) AS fPutRightSum, ISNULL(PR.fErrCount, 0) AS fErrCount,   
                      ISNULL(PR.fWarnCount, 0) AS fWarnCount, ISNULL(PR.fLastRecTime, CONVERT(varchar(10), GETDATE(), 120)) AS fLastRecTime, P.fCtrlPosID, P.fLimitCounts, P.fWVer,   
                      P.fBVer, P.fRecSerialNo, P.fLimitMoneyEnabled, P.fLimitCountEnabled, P.fDiscountEnabled, P.fFirstPurseID, P.fSecondPurseID  
FROM         dbo.T_B_Pos AS P LEFT OUTER JOIN  
                          (SELECT     fPosID, CONVERT(varchar(10), fRecDate, 120) AS fRecDate, MAX(fLastRecTime) AS fLastRecTime, ISNULL(SUM(fRecCount), 0) AS fRecCount,   
                                                   ISNULL(SUM(fConsSum), 0) AS fConsSum, ISNULL(SUM(fSaveCount), 0) AS fSaveCount, ISNULL(SUM(fSaveSum), 0) AS fSaveSum,   
                                                   ISNULL(SUM(fTakeCount), 0) AS fTakeCount, ISNULL(SUM(fTakeSum), 0) AS fTakeSum, ISNULL(SUM(fPutRightCount), 0) AS fPutRightCount,   
                                                   ISNULL(SUM(fPutRightSum), 0) AS fPutRightSum, ISNULL(SUM(fErrCount), 0) AS fErrCount, ISNULL(SUM(fWarnCount), 0) AS fWarnCount  
                            FROM          dbo.T_B_PosDayRecs  
                            WHERE      (CONVERT(varchar(10), fRecDate, 120) = CONVERT(varchar(10), GETDATE(), 120))  
                            GROUP BY fPosID, CONVERT(varchar(10), fRecDate, 120)) AS PR ON P.fPosID = PR.fPosID LEFT OUTER JOIN  
                      dbo.T_B_PosType AS PT ON P.fPosType = PT.fPosType  
                      
GO   


--VIEW_EDIT_3 修改视图V_C_SUM_OPER

if exists (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[V_C_SUM_OPER]') and xtype='V' )
drop view V_C_SUM_OPER
GO
CREATE VIEW [dbo].[V_C_SUM_OPER]  
AS  
SELECT fKey,
       fOperID,
       fDate,
       fAppID,
       SUM(CASE WHEN fTType = 0 AND fCType = 0 THEN fCount ELSE 0 END)                         AS [消费|次],
       SUM(CASE
               WHEN fTType = 0 AND
                    fCType = 0 THEN fMoney
               ELSE 0.00 END)                                                                  AS [消费|金额],
       SUM(CASE WHEN fTType = 1 AND fCType = 0 AND p.fPurseType = 0 THEN fCount ELSE 0 END)    AS [金额充值|次],
       SUM(CASE WHEN fTType = 1 AND fCType = 0 AND p.fPurseType = 0 THEN fMoney ELSE 0.00 END) AS [金额充值|金额],
       SUM(CASE
               WHEN fTType = 1 AND
                    fCType = 4 THEN fMoney
               ELSE 0.00 END)                                                                  AS [存款|管理费],
       SUM(CASE WHEN fTType = 2 AND fCType = 0 AND p.fPurseType = 0 THEN fCount ELSE 0 END)    AS [金额取款|次],
       SUM(CASE WHEN fTType = 2 AND fCType = 0 AND p.fPurseType = 0 THEN fMoney ELSE 0.00 END) AS [金额取款|金额],
       SUM(CASE WHEN fTType = 1 AND fCType = 0 AND p.fPurseType = 1 THEN fCount ELSE 0 END)    AS [次数充值|次],
       SUM(CASE WHEN fTType = 1 AND fCType = 0 AND p.fPurseType = 1 THEN fMoney ELSE 0 END)	   AS [次数充值|金额],
       SUM(CASE WHEN fTType = 2 AND fCType = 0 AND p.fPurseType = 1 THEN fCount ELSE 0 END)    AS [次数取款|次],
       SUM(CASE WHEN fTType = 2 AND fCType = 0 AND p.fPurseType = 1 THEN fMoney ELSE 0 END)    AS [次数取款|金额],
       SUM(CASE WHEN fTType = 3 AND fCType = 0 AND p.fPurseType = 0 THEN fCount ELSE 0 END)    AS [金额补助|次],
       SUM(CASE WHEN fTType = 3 AND fCType = 0 AND p.fPurseType = 0 THEN fMoney ELSE 0.00 END) AS [金额补助|金额],
       SUM(CASE WHEN fTType = 3 AND fCType = 0 AND p.fPurseType = 1 THEN fCount ELSE 0 END)    AS [次数补助|次],
       SUM(CASE WHEN fTType = 3 AND fCType = 0 AND p.fPurseType = 1 THEN fMoney ELSE 0 END)    AS [次数补助|金额],
       SUM(CASE WHEN fTType = 4 AND fCType = 0 THEN fCount ELSE 0 END)                         AS [挂失|次],
       SUM(CASE WHEN fTType = 4 AND fCType = 0 THEN fMoney ELSE 0.00 END)                      AS [挂失|金额],
       SUM(CASE WHEN fTType = 4 AND fCType = 1 THEN fMoney ELSE 0.00 END)                      AS [挂失|手续费],
       SUM(CASE WHEN fTType = 5 AND fCType = 0 THEN fCount ELSE 0 END)						   AS [解挂|次],
       SUM(CASE WHEN fTType = 5 AND fCType = 0 THEN fMoney ELSE 0.00 END)                      AS [解挂|金额],
       SUM(CASE
               WHEN fTType = 5 AND
                    fCType = 1 THEN fMoney
               ELSE 0.00 END)                                                                  AS [解挂|手续费],
       SUM(CASE WHEN fTType = 6 AND fCType = 0 THEN fCount ELSE 0 END)                         AS [开户|次],
       SUM(CASE WHEN fTType = 6 AND fCType = 0 THEN fMoney ELSE 0.00 END)                      AS [开户|金额],
       SUM(CASE
               WHEN fTType = 6 AND
                    fCType = 2 THEN fMoney
               ELSE 0.00 END)                                                                  AS [开户|卡费],
       SUM(CASE WHEN fTType = 6 AND fCType = 3 THEN fMoney ELSE 0.00 END)                      AS [开户|押金],
       SUM(CASE WHEN fTType = 6 AND fCType = 4 THEN fMoney ELSE 0.00 END)                      AS [开户|管理费],
       SUM(CASE WHEN fTType = 7 AND fCType = 0 THEN fCount ELSE 0 END)
                                                                                               AS [有卡撤户|次],
       SUM(CASE WHEN fTType = 7 AND fCType = 0 THEN fMoney ELSE 0.00 END)                      AS [有卡撤户|金额],
       SUM(CASE
               WHEN fTType = 7 AND
                    fCType = 1 THEN fMoney
               ELSE 0.00 END)                                                                  AS [有卡撤户|手续费],
       SUM(CASE WHEN fTType = 7 AND fCType = 3 THEN fMoney ELSE 0.00 END)                      AS [有卡撤户|押金],
       SUM(CASE WHEN fTType = 8 AND fCType = 0 THEN fCount ELSE 0 END)                         AS [纠错|次],
       SUM(CASE WHEN fTType = 8 AND fCType = 0 THEN fMoney ELSE 0.00 END)
                                                                                               AS [纠错|金额],
       SUM(CASE WHEN fTType = 9 AND fCType = 0 THEN fCount ELSE 0 END)                         AS [换卡|次],
       SUM(CASE
               WHEN fTType = 9 AND
                    fCType = 0 THEN fMoney
               ELSE 0.00 END)                                                                  AS [换卡|金额],
       SUM(CASE WHEN fTType = 9 AND fCType = 1 THEN fMoney ELSE 0.00 END)                      AS [换卡|手续费],
       SUM(CASE WHEN fTType = 10 AND fCType = 0 THEN fCount ELSE 0 END)                        AS [补卡|次],
       SUM(CASE WHEN fTType = 10 AND fCType = 0 THEN fMoney ELSE 0.00 END)
                                                                                               AS [补卡|金额],
       SUM(CASE WHEN fTType = 10 AND fCType = 1 THEN fMoney ELSE 0.00 END)                     AS [补卡|手续费],
       SUM(CASE
               WHEN fTType = 10 AND
                    fCType = 2 THEN fMoney
               ELSE 0.00 END)                                                                  AS [补卡|卡费],
       SUM(CASE WHEN fTType = 11 AND fCType = 0 THEN fCount ELSE 0 END)                        AS [有卡变更|次],
       SUM(CASE WHEN fTType = 11 AND fCType = 0 THEN fMoney ELSE 0.00 END)                     AS [有卡变更|金额],
       SUM(CASE
               WHEN fTType = 21 AND
                    fCType = 0 THEN fCount
               ELSE 0 END)                                                                     AS [自动挂失|次],
       SUM(CASE WHEN fTType = 21 AND fCType = 0 THEN fMoney ELSE 0.00 END)                     AS [自动挂失|金额],
       SUM(CASE WHEN fTType = 22 AND fCType = 0 THEN fCount ELSE 0 END)                        AS [无卡变更|次],
       SUM(CASE
               WHEN fTType = 22 AND
                    fCType = 0 THEN fMoney
               ELSE 0.00 END)                                                                  AS [无卡变更|金额],
       SUM(CASE WHEN fTType = 23 AND fCType = 0 THEN fCount ELSE 0 END)                        AS [人工冻结|次],
       SUM(CASE WHEN fTType = 23 AND fCType = 0 THEN fMoney ELSE 0.00 END)                     AS [人工冻结|金额],
       SUM(CASE
               WHEN fTType = 24 AND
                    fCType = 0 THEN fCount
               ELSE 0 END)                                                                     AS [自动冻结|次],
       SUM(CASE WHEN fTType = 24 AND fCType = 0 THEN fMoney ELSE 0.00 END)                     AS [自动冻结|金额],
       SUM(CASE WHEN fTType = 25 AND fCType = 0 THEN fCount ELSE 0 END)                        AS [无卡撤户|次],
       SUM(CASE
               WHEN fTType = 25 AND
                    fCType = 0 THEN fMoney
               ELSE 0.00 END)                                                                  AS [无卡撤户|金额],
       SUM(CASE WHEN fTType = 25 AND fCType = 1 THEN fMoney ELSE 0.00 END)                     AS [无卡撤户|手续费],
       SUM(CASE WHEN fTType = 25 AND fCType = 3 THEN fMoney ELSE 0.00 END)                     AS [无卡撤户|押金],
       SUM(CASE
               WHEN fTType = 26 AND
                    fCType = 0 THEN fCount
               ELSE 0 END)                                                                     AS [补发卡|次],
       SUM(CASE WHEN fTType = 26 AND fCType = 0 THEN fMoney ELSE 0.00 END)                     AS [补发卡|金额],
       SUM(CASE WHEN fTType = 27 AND fCType = 0 THEN fCount ELSE 0 END)                        AS [解冻|次],
       SUM(CASE WHEN fTType = 27 AND fCType = 0 THEN fMoney ELSE 0.00 END)
                                                                                               AS [解冻|金额],
       SUM(CASE WHEN fTType = 28 AND fCType = 0 THEN fCount ELSE 0 END)                        AS [圈存|次],
       SUM(CASE
               WHEN fTType = 28 AND
                    fCType = 0 THEN fMoney
               ELSE 0.00 END)                                                                  AS [圈存|金额],
       SUM(CASE WHEN fTType = 28 AND fCType = 4 THEN fMoney ELSE 0.00 END)                     AS [圈存|管理费],
       SUM(CASE WHEN fTType = 29 AND fCType = 0 THEN fCount ELSE 0 END)                        AS [圈存补款|次],
       SUM(CASE
               WHEN fTType = 29 AND
                    fCType = 0 THEN fMoney
               ELSE 0.00 END)                                                                  AS [圈存补款|金额],
       SUM(CASE WHEN fTType = 30 AND fCType = 0 THEN fCount ELSE 0 END)                        AS [圈提|次],
       SUM(CASE WHEN fTType = 30 AND fCType = 0 THEN fMoney ELSE 0.00 END)                     AS [圈提|金额],
       SUM(CASE WHEN fTType = 31 AND fCType = 0 THEN fCount ELSE 0 END)
                                                                                               AS [优惠|次],
       SUM(CASE WHEN fTType = 31 AND fCType = 0 THEN fMoney ELSE 0.00 END)                     AS [优惠|金额],
       SUM(CASE
               WHEN fTType = 32 AND
                    fCType = 0 THEN fCount
               ELSE 0 END)                                                                     AS [计次|次],
       SUM(CASE WHEN fTType = 32 AND fCType = 0 THEN fMoney ELSE 0.00 END)                     AS [计次|金额],
       SUM(CASE WHEN fTType = 33 AND fCType = 0 THEN fCount ELSE 0 END)                        AS [转入|次],
       SUM(CASE WHEN fTType = 33 AND fCType = 0 THEN fMoney ELSE 0.00 END)
                                                                                               AS [转入|金额],
       SUM(CASE WHEN fTType = 34 AND fCType = 0 THEN fCount ELSE 0 END)                        AS [转出|次],
       SUM(CASE
               WHEN fTType = 34 AND
                    fCType = 0 THEN fMoney
               ELSE 0.00 END)                                                                  AS [转出|金额],
       SUM(CASE WHEN fTType = 35 AND fCType = 0 THEN fCount ELSE 0 END)                        AS [删除资料|次],
       SUM(CASE WHEN fTType = 35 AND fCType = 0 THEN fMoney ELSE 0.00 END)                     AS [删除资料|金额],
       SUM(CASE
               WHEN fTType = 36 AND
                    fCType = 0 THEN fCount
               ELSE 0 END)                                                                     AS [销卡|次],
       SUM(CASE WHEN fTType = 36 AND fCType = 0 THEN fMoney ELSE 0.00 END)                     AS [销卡|金额],
       SUM(CASE WHEN fTType = 37 AND fCType = 0 THEN fCount ELSE 0 END)                        AS [补助清除|次],
       SUM(CASE WHEN fTType = 37 AND fCType = 0 THEN fMoney ELSE 0.00 END)                     AS [补助清除|金额]
FROM dbo.T_C_SUM_OPER S
         LEFT JOIN T_B_PurseCode P ON P.fPurseCode = S.fAppID
GROUP BY fKey, fOperID, fDate, fAppID

GO

--VIEW_EDIT_4 修改视图V_C_SUM_Pos

if exists (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[V_C_SUM_Pos]') and xtype='V' )
drop view V_C_SUM_Pos
GO
Create  view [dbo].[V_C_SUM_Pos] as    
select    
   fKey,    
   fPosID,
   fPurseID,    
   fDate,    
   fMealID,    
   SUM(CASE WHEN fTType in(0,17) AND fCType = 0 THEN fCount ELSE 0 END) as [消费|次],    
   SUM(CASE WHEN fTType in(0,17) AND fCType = 0 THEN fMoney ELSE 0.00 END) as [消费|金额],    
   SUM(CASE WHEN fTType = 1 AND fCType = 0 THEN fCount ELSE 0 END) as [存款|次],    
   SUM(CASE WHEN fTType = 1 AND fCType = 0 THEN fMoney ELSE 0.00 END) as [存款|金额],    
   SUM(CASE WHEN fTType = 2 AND fCType = 0 THEN fCount ELSE 0 END) as [取款|次],    
   SUM(CASE WHEN fTType = 2 AND fCType = 0 THEN fMoney ELSE 0.00 END) as [取款|金额],    
   SUM(CASE WHEN fTType = 3 AND fCType = 0 THEN fCount ELSE 0 END) as [补助|次],    
   SUM(CASE WHEN fTType = 3 AND fCType = 0 THEN fMoney ELSE 0.00 END) as [补助|金额],    
   SUM(CASE WHEN fTType = 8 AND fCType = 0 THEN fCount ELSE 0 END) as [纠错|次],    
   SUM(CASE WHEN fTType = 8 AND fCType = 0 THEN fMoney ELSE 0.00 END) as [纠错|金额],    
   SUM(CASE WHEN fTType = 28 AND fCType = 0 THEN fCount ELSE 0 END) as [圈存|次],    
   SUM(CASE WHEN fTType = 28 AND fCType = 0 THEN fMoney ELSE 0.00 END) as [圈存|金额],    
   SUM(CASE WHEN fTType = 29 AND fCType = 0 THEN fCount ELSE 0 END) as [圈存补款|次],    
   SUM(CASE WHEN fTType = 29 AND fCType = 0 THEN fMoney ELSE 0.00 END) as [圈存补款|金额],    
   SUM(CASE WHEN fTType = 30 AND fCType = 0 THEN fCount ELSE 0 END) as [圈提|次],    
   SUM(CASE WHEN fTType = 30 AND fCType = 0 THEN fMoney ELSE 0.00 END) as [圈提|金额],    
   SUM(CASE WHEN fTType = 31 AND fCType = 0 THEN fCount ELSE 0 END) as [优惠|次],    
   SUM(CASE WHEN fTType = 31 AND fCType = 0 THEN fMoney ELSE 0.00 END) as [优惠|金额],    
   SUM(CASE WHEN fTType = 32 AND fCType = 0 THEN fCount ELSE 0 END) as [计次|次],    
   SUM(CASE WHEN fTType = 32 AND fCType = 0 THEN fMoney ELSE 0.00 END) as [计次|金额]    
from    
   T_C_SUM_Pos    
group by    
   fKey,    
   fPosID, 
   fPurseID,   
   fDate,    
   fMealID  
GO

--PROC_ADD_1 增加后台处理个人消费汇总存储过程SP_GetEmpSumInfo_Backstage
if exists(select  * from sys.all_objects where name='SP_GetEmpSumInfo_Backstage' and type='P')
drop procedure SP_GetEmpSumInfo_Backstage
go
-- exec SP_GetEmpSumInfo_Backstage '2021-06-24','00000860',1
create  procedure [dbo].[SP_GetEmpSumInfo_Backstage]       
    @datetime datetime,      
    @AccountID varchar(8),      
    @PurseID int    
as
begin 
  --返回结果临时表   
  create table #Result
  (
				faccountid varchar(10),
				fpurseID int,
				famount1 numeric(9,2) not null default 0.00,
				fcount1 int not null default 0,
				famountlimit1 numeric(9,2)not null default 0.00,
				fcountlimit1 int not null default 0,
				famount2 numeric(9,2)not null default 0.00,
				fcount2 int not null default 0,
				famountlimit2 numeric(9,2)not null default 0.00,
				fcountlimit2 int not null default 0,
				famount3 numeric(9,2)not null default 0.00,
				fcount3 int  not null default 0,
				famountlimit3 numeric(9,2)not null default 0.00,
				fcountlimit3 int not null default 0,
				famount4 numeric(9,2)not null default 0.00,
				fcount4 int  not null default 0,
				famountlimit4 numeric(9,2)not null default 0.00,
				fcountlimit4 int not null default 0,
				famount5 numeric(9,2)not null default 0.00,
				fcount5 int  not null default 0,
				famountlimit5 numeric(9,2)not null default 0.00,
				fcountlimit5 int not null default 0,
				famount6 numeric(9,2)not null default 0.00,
				fcount6 int  not null default 0,
				famountlimit6 numeric(9,2)not null default 0.00,
				fcountlimit6 int not null default 0,
				famount7 numeric(9,2)not null default 0.00,
				fcount7 int  not null default 0,
				famountlimit7 numeric(9,2)not null default 0.00,
				fcountlimit7 int not null default 0,
				famount8 numeric(9,2)not null default 0.00,
				fcount8 int  not null default 0,
				famountlimit8 numeric(9,2)not null default 0.00,
				fcountlimit8 int not null default 0,
				famount_d numeric(9,2)not null default 0.00,
				fcount_d int  not null default 0,
				famountlimit_d numeric(9,2)not null default 0.00,
				fcountlimit_d int not null default 0,
				famount_w numeric(9,2)not null default 0.00,
				fcount_w  int  not null default 0,
				famountlimit_w  numeric(9,2)not null default 0.00,
				fcountlimit_w  int not null default 0,
				famount_m  numeric(9,2)not null default 0.00,
				fcount_m  int  not null default 0,
				famountlimit_m  numeric(9,2)not null default 0.00,
				fcountlimit_m  int not null default 0,
				famount_y  numeric(9,2)not null default 0.00,
				fcount_y int  not null default 0,
				famountlimit_y numeric(9,2)not null default 0.00,
				fcountlimit_y int not null default 0,
				fputrightamount_d numeric(9,2)not null default 0.00,
				fputrightcount_d int not null default 0
  )

  declare @curday varchar(10)
  declare @curweek varchar(8) 
  declare @curmonth varchar(8)
  declare @curyear varchar(8)
  declare @TableName_SE varchar(30)
  declare @TabSQL varchar(4000)
 
  set @curweek=right('00'+cast((datepart(wk,@datetime) - datepart(wk,convert(varchar(7),@datetime,120) + '-01') + 1) as varchar(2)),2)--传入日期是当月第几周(04)
  set @curmonth=right('00'+cast(MONTH(@datetime) as varchar(2)),2)--传入日期当前月份(202106)
  set @curyear=cast(year(@datetime) as varchar(4))--传入日期当前年份(2021)
  set @curweek=@curyear+@curmonth+@curweek  --例：20210604 (2021年第6月第4周)
  set @curmonth=@curyear+@curmonth+'00'     --例：20210600 (2021年第6月) 
  set @curyear=@curyear+'0000'              --例：20210000 (2021年) 
  set @curday=CONVERT(varchar(10),@datetime,120)
   
  --建临时表
  select  fkey,faccountID,fdate,fpurseID,fmealID,famount,fcount,famountLimit,fcountLimit  into #T_C_CashEmp   from T_C_CashEmp   where 1=2
  select  fkey,faccountID,fvalue,fpurseID,fmealID,famount,fcount,famountLimit,fcountLimit  into #T_C_CashEmpEx from T_C_CashEmpEx where 1=2
  
  --过滤查询条件 
  if (@AccountID='') and (@PurseID=0)
  begin
    insert into #T_C_CashEmp select  fkey,faccountID,fdate,fpurseID,fmealID,famount,fcount,famountLimit,fcountLimit  from T_C_CashEmp where convert(varchar(10),fdate,120)=@curday
    insert into  #T_C_CashEmpEx select fkey,faccountID,fvalue,fpurseID,fmealID,famount,fcount,famountLimit,fcountLimit  from T_C_CashEmpEx where fvalue in (@curweek,@curmonth,@curyear)
  end
  else if (@AccountID<>'') and (@PurseID=0)
		begin
				insert into  #T_C_CashEmp select  fkey,faccountID,fdate,fpurseID,fmealID,famount,fcount,famountLimit,fcountLimit  from T_C_CashEmp where faccountID=@AccountID and convert(varchar(10),fdate,120)=@curday
				insert into  #T_C_CashEmpEx select  fkey,faccountID,fvalue,fpurseID,fmealID,famount,fcount,famountLimit,fcountLimit  from T_C_CashEmpEx where faccountID=@AccountID and fvalue in (@curweek,@curmonth,@curyear)
		end
  else if(@AccountID<>'') and (@PurseID<>0)
 begin
    insert into  #T_C_CashEmp select  fkey,faccountID,fdate,fpurseID,fmealID,famount,fcount,famountLimit,fcountLimit  from T_C_CashEmp where faccountID=@AccountID and convert(varchar(10),fdate,120)=@curday and fpurseID=@PurseID
		 	insert into  #T_C_CashEmpEx select  fkey,faccountID,fvalue,fpurseID,fmealID,famount,fcount,famountLimit,fcountLimit  from T_C_CashEmpEx where faccountID=@AccountID and fpurseID=@PurseID and  fvalue in (@curweek,@curmonth,@curyear) 
 end
  --消费按餐次汇总
  declare @fmealid varchar(3)
  declare  cur_mealid cursor for        
    select  fMeal_Id from T_B_MealSet    
  open cur_mealid        
  fetch next  from cur_mealid into @fmealid    
  while @@fetch_status = 0        
  begin     
     if @fmealid='001'                              
								insert into #Result  select  faccountID,fpurseID,famount,fcount,famountLimit,fcountLimit,  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
								from #T_C_CashEmp where fmealID=@fmealid
     if @fmealid='002'
							insert into #Result  select  faccountID,fpurseID   ,0,0,0,0,famount,fcount,famountLimit,fcountLimit,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
							from #T_C_CashEmp where fmealID=@fmealid
     if @fmealid='003'
							insert into #Result  select  faccountID,fpurseID   ,0,0,0,0,0,0,0,0,famount,fcount,famountLimit,fcountLimit,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
							from #T_C_CashEmp where fmealID=@fmealid
     if @fmealid='004'
							insert into #Result  select  faccountID,fpurseID   ,0,0,0,0,0,0,0,0,0,0,0,0,famount,fcount,famountLimit,fcountLimit,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
							from #T_C_CashEmp where fmealID=@fmealid
     if @fmealid='005'
							insert into #Result  select  faccountID,fpurseID   ,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,famount,fcount,famountLimit,fcountLimit,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
							from #T_C_CashEmp where fmealID=@fmealid
     if @fmealid='006'
							insert into #Result  select  faccountID,fpurseID   ,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,famount,fcount,famountLimit,fcountLimit,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
							from #T_C_CashEmp where fmealID=@fmealid
     if @fmealid='007'
							insert into #Result  select  faccountID,fpurseID   ,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,famount,fcount,famountLimit,fcountLimit,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
							from #T_C_CashEmp where fmealID=@fmealid
     if @fmealid='008'
							insert into #Result  select  faccountID,fpurseID   ,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,famount,fcount,famountLimit,fcountLimit,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
							from #T_C_CashEmp where  fmealID=@fmealid
  fetch next from cur_mealid into @fmealid    
  end        
  close cur_mealid        
  deallocate  cur_mealid
  
  --消费按天汇总
  insert into #Result  select  faccountID,fpurseID,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,sum(famount),sum(fcount),sum(famountLimit),sum(fcountLimit),0,0,0,0,0,0,0,0,0,0,0,0,0,0
							from #T_C_CashEmp where fdate=@curday  group by faccountID,fpurseID
	 --消费按周汇总
  insert into #Result  select  faccountID,fpurseID,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,famount,fcount,famountLimit,fcountLimit,0,0,0,0,0,0,0,0,0,0
	 						from #T_C_CashEmpEx where fvalue=@curweek 
	--消费按月汇总
  insert into #Result  select  faccountID,fpurseID,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,famount,fcount,famountLimit,fcountLimit,0,0,0,0,0,0
							from #T_C_CashEmpEx where fvalue=@curmonth
 	--消费按年汇总
  insert into #Result  select  faccountID,fpurseID,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,famount,fcount,famountLimit,fcountLimit,0,0
							from #T_C_CashEmpEx where fvalue=@curyear
		
		EXEC SP_Wst_CheckSumEmpTable @datetime, @TableName_SE output  
		
  	--纠错按天汇总
  set @TabSQL='insert into #Result select  fAccountID,fPurseID,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,fPutRightCount,fPutRightMoney from '+@TableName_SE+' where fDate='''+@curday+''''  
  if @AccountID <>'' 
		   set @TabSQL=@TabSQL+' and fAccountID='''+@AccountID+''''
	 if @PurseID>0 
	    set @TabSQL=@TabSQL+' and fPurseID='+CAST(@PurseID as varchar(2))
	 print @TabSQL
		EXEC(@TabSQL) 
		
	
  --insert into #Result  select  faccountID,fpurseID,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,famount,fcount,famountLimit,fcountLimit,0,0
		--					from #T_C_CashEmpEx where fvalue=@curyear					
							
		
  
  SELECT fAccountID,fPurseID,      
      sum(famount1) AS famount1, sum(fcount1) AS fcount1,               --餐次1消费金额，餐次1消费次数 
      sum(famount2) AS famount2, sum(fcount2) AS fcount2,               --餐次2消费金额，餐次2消费次数   
      sum(famount3) AS famount3, sum(fcount3) AS fcount3,               --餐次3消费金额，餐次3消费次数 
      sum(famount4) AS famount4, sum(fcount4) AS fcount4,               --餐次4消费金额，餐次4消费次数   
      sum(famount5) AS famount5, sum(fcount5) AS fcount5,               --餐次5消费金额，餐次5消费次数 
      sum(famount6) AS famount6, sum(fcount6) AS fcount6,               --餐次6消费金额，餐次6消费次数 
      sum(famount7) AS famount7, sum(fcount7) AS fcount7,               --餐次7消费金额，餐次7消费次数  
      sum(famount8) AS famount8, sum(fcount8) AS fcount8,               --餐次8消费金额，餐次8消费次数   
      sum(famountlimit1) AS famountlimit1,   sum(fcountlimit1) AS fcountlimit1, --餐次1限额消费金额，餐次1限额消费次数 
      sum(famountlimit2) AS famountlimit2,   sum(fcountlimit2) AS fcountlimit2, --餐次2限额消费金额，餐次2限额消费次数    
      sum(famountlimit3) AS famountlimit3,   sum(fcountlimit3) AS fcountlimit3, --餐次3限额消费金额，餐次3限额消费次数 
      sum(famountlimit4) AS famountlimit4,   sum(fcountlimit4) AS fcountlimit4, --餐次4限额消费金额，餐次4限额消费次数      
      sum(famountlimit5) AS famountlimit5,   sum(fcountlimit5) AS fcountlimit5, --餐次5限额消费金额，餐次5限额消费次数      
      sum(famountlimit6) AS famountlimit6,   sum(fcountlimit6) AS fcountlimit6, --餐次6限额消费金额，餐次6限额消费次数  
      sum(famountlimit7) AS famountlimit7,   sum(fcountlimit7) AS fcountlimit7, --餐次7限额消费金额，餐次7限额消费次数     
      sum(famountlimit8) AS famountlimit8,   sum(fcountlimit8) AS fcountlimit8, --餐次8限额消费金额，餐次8限额消费次数 
      sum(famount_d) as famount_d,  sum(fcount_d) as fcount_d,              --消费金额按天汇总，消费次数按天汇总
      sum(famount_w) as famount_w,  sum(fcount_w) as fcount_w,              --消费金额按周汇总，消费次数按周汇总
      sum(famount_m) as famount_m,  sum(fcount_m) as fcount_m,              --消费金额按月汇总，消费次数按月汇总
      sum(famount_y) as famount_y,  sum(fcount_y) as fcount_y,              --消费金额按年汇总，消费次数按年汇总  
      sum(famountlimit_d) as famountlimit_d,  sum(fcountlimit_d) as fcountlimit_d,  --消费金额限额按天汇总，消费次数限额按天汇总
      sum(famountlimit_w) as famountlimit_w,  sum(fcountlimit_w) as fcountlimit_w,  --消费金额限额按周汇总，消费次数限额按周汇总
      sum(famountlimit_m) as famountlimit_m,  sum(fcountlimit_m) as fcountlimit_m,  --消费金额限额按月汇总，消费次数限额按月汇总
      sum(famountlimit_y) as famountlimit_y,  sum(fcountlimit_y) as fcountlimit_y,   --消费金额限额按年汇总，消费次数限额按年汇总
				  sum(fputrightamount_d) as fputrightamount_d,  sum(fputrightcount_d) as fputrightcount_d --纠错 
    FROM #Result group by fAccountID,fPurseID order by fAccountID,fPurseID
  
end
go
--PROC_ADD_2 增加界面处理个人消费汇总存储过程SP_GetEmpSumInfo_Interface
if exists(select  * from sys.all_objects where name='SP_GetEmpSumInfo_Interface' and type='P')
drop procedure SP_GetEmpSumInfo_Interface
go
-- exec SP_GetEmpSumInfo_Interface '2021-06-24','00000859',1
create  procedure [dbo].[SP_GetEmpSumInfo_Interface]       
    @datetime datetime,      
    @AccountID varchar(8),      
    @PurseID int    
as
begin 
  --返回结果临时表   
  create table #Result
  (
				faccountid varchar(10),
				fpurseID int,
				famount1 numeric(9,2) not null default 0.00,
				fcount1 int not null default 0,
				famountlimit1 numeric(9,2)not null default 0.00,
				fcountlimit1 int not null default 0,
				famount2 numeric(9,2)not null default 0.00,
				fcount2 int not null default 0,
				famountlimit2 numeric(9,2)not null default 0.00,
				fcountlimit2 int not null default 0,
				famount3 numeric(9,2)not null default 0.00,
				fcount3 int  not null default 0,
				famountlimit3 numeric(9,2)not null default 0.00,
				fcountlimit3 int not null default 0,
				famount4 numeric(9,2)not null default 0.00,
				fcount4 int  not null default 0,
				famountlimit4 numeric(9,2)not null default 0.00,
				fcountlimit4 int not null default 0,
				famount5 numeric(9,2)not null default 0.00,
				fcount5 int  not null default 0,
				famountlimit5 numeric(9,2)not null default 0.00,
				fcountlimit5 int not null default 0,
				famount6 numeric(9,2)not null default 0.00,
				fcount6 int  not null default 0,
				famountlimit6 numeric(9,2)not null default 0.00,
				fcountlimit6 int not null default 0,
				famount7 numeric(9,2)not null default 0.00,
				fcount7 int  not null default 0,
				famountlimit7 numeric(9,2)not null default 0.00,
				fcountlimit7 int not null default 0,
				famount8 numeric(9,2)not null default 0.00,
				fcount8 int  not null default 0,
				famountlimit8 numeric(9,2)not null default 0.00,
				fcountlimit8 int not null default 0,
				
				fConsCountD int not null default 0,
				fConsMoneyD numeric(9,2) not null default 0.00,
				fSaveCountD int not null default 0,
				fSaveMoneyD numeric(9,2) not null default 0.00,
				fTakeCountD int not null default 0,
				fTakeMoneyD numeric(9,2) not null default 0.00,
				fSubCountD int not null default 0,
				fSubMoneyD numeric(9,2) not null default 0.00,
				fClearCountD int not null default 0,
				fClearMoneyD numeric(9,2) not null default 0.00,
				fPutRightCountD int not null default 0,
				fPutRightMoneyD numeric(9,2) not null default 0.00,
				fConsCountM int not null default 0,
				fConsMoneyM numeric(9,2) not null default 0.00,
				fSaveCountM int not null default 0,
				fSaveMoneyM numeric(9,2) not null default 0.00,
				fTakeCountM int not null default 0,
				fTakeMoneyM numeric(9,2) not null default 0.00,
				fSubCountM int not null default 0,
				fSubMoneyM numeric(9,2) not null default 0.00,
				fClearCountM int not null default 0,
				fClearMoneyM numeric(9,2) not null default 0.00,
				fPutRightCountM int not null default 0,
				fPutRightMoneyM numeric(9,2) not null default 0.00
				
  )

  declare @curday varchar(10)
  declare @curweek varchar(8) 
  declare @curmonth varchar(8)
  declare @curyear varchar(8)
  declare @TableName_SE varchar(30)
  declare @TabSQL varchar(4000)
  DECLARE @Where varchar(4000)
  
  declare @sDateBegin varchar(20)
  declare @sDateEnd varchar(20)
  
  
  set @Where=''
  set @curweek=right('00'+cast((datepart(wk,@datetime) - datepart(wk,convert(varchar(7),@datetime,120) + '-01') + 1) as varchar(2)),2)--传入日期是当月第几周(04)
  set @curmonth=right('00'+cast(MONTH(@datetime) as varchar(2)),2)--传入日期当前月份(202106)
  set @curyear=cast(year(@datetime) as varchar(4))--传入日期当前年份(2021)
  set @curweek=@curyear+@curmonth+@curweek  --例：20210604 (2021年第6月第4周)
  set @curmonth=@curyear+@curmonth+'00'     --例：20210600 (2021年第6月) 
  set @curyear=@curyear+'0000'              --例：20210000 (2021年) 
  set @curday=CONVERT(varchar(10),@datetime,120)
  SET @sDateBegin = DATENAME(YYYY, @datetime) + '-' + DATENAME(MM, @datetime) + '-1'      
  SET @sDateEnd = DATENAME(YYYY, DATEADD(MM, 1, @datetime)) + '-' + DATENAME(MM, DATEADD(MM, 1, @datetime)) + '-1' 
  
  --建临时表
  select  fkey,faccountID,fdate,fpurseID,fmealID,famount,fcount,famountLimit,fcountLimit  into #T_C_CashEmp   from T_C_CashEmp   where 1=2
  
  --过滤查询条件 
  if (@AccountID='') and (@PurseID=0)
  begin
    insert into #T_C_CashEmp select  fkey,faccountID,fdate,fpurseID,fmealID,famount,fcount,famountLimit,fcountLimit  from T_C_CashEmp where convert(varchar(10),fdate,120)=@curday
  end
  else if (@AccountID<>'') and (@PurseID=0)
		begin
				insert into  #T_C_CashEmp select  fkey,faccountID,fdate,fpurseID,fmealID,famount,fcount,famountLimit,fcountLimit  from T_C_CashEmp where faccountID=@AccountID and convert(varchar(10),fdate,120)=@curday
				set @Where=@Where+' and fAccountID ='''+@AccountID+''''
		end
  else if(@AccountID<>'') and (@PurseID<>0)
 begin
    insert into  #T_C_CashEmp select  fkey,faccountID,fdate,fpurseID,fmealID,famount,fcount,famountLimit,fcountLimit  from T_C_CashEmp where faccountID=@AccountID and convert(varchar(10),fdate,120)=@curday and fpurseID=@PurseID
    set @Where=@Where+' and fAccountID ='''+@AccountID+''' and fPurseID = '+CAST(@PurseID as varchar(2))
 end
  --消费按餐次汇总
  declare @fmealid varchar(3)
  declare  cur_mealid cursor for        
    select  fMeal_Id from T_B_MealSet    
  open cur_mealid        
  fetch next  from cur_mealid into @fmealid    
  while @@fetch_status = 0        
  begin     
     if @fmealid='001'                              
								insert into #Result  select  faccountID,fpurseID,famount,fcount,famountLimit,fcountLimit,  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
								from #T_C_CashEmp where fmealID=@fmealid
     if @fmealid='002'
							insert into #Result  select  faccountID,fpurseID   ,0,0,0,0,famount,fcount,famountLimit,fcountLimit,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
							from #T_C_CashEmp where fmealID=@fmealid
     if @fmealid='003'
							insert into #Result  select  faccountID,fpurseID   ,0,0,0,0,0,0,0,0,famount,fcount,famountLimit,fcountLimit,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
							from #T_C_CashEmp where fmealID=@fmealid
     if @fmealid='004'
							insert into #Result  select  faccountID,fpurseID   ,0,0,0,0,0,0,0,0,0,0,0,0,famount,fcount,famountLimit,fcountLimit,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
							from #T_C_CashEmp where fmealID=@fmealid
     if @fmealid='005'
							insert into #Result  select  faccountID,fpurseID   ,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,famount,fcount,famountLimit,fcountLimit,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
							from #T_C_CashEmp where fmealID=@fmealid
     if @fmealid='006'
							insert into #Result  select  faccountID,fpurseID   ,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,famount,fcount,famountLimit,fcountLimit,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
							from #T_C_CashEmp where fmealID=@fmealid
     if @fmealid='007'
							insert into #Result  select  faccountID,fpurseID   ,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,famount,fcount,famountLimit,fcountLimit,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
							from #T_C_CashEmp where fmealID=@fmealid
     if @fmealid='008'
							insert into #Result  select  faccountID,fpurseID   ,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,famount,fcount,famountLimit,fcountLimit,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
							from #T_C_CashEmp where  fmealID=@fmealid
  fetch next from cur_mealid into @fmealid    
  end        
  close cur_mealid        
  deallocate  cur_mealid
  
		
		EXEC SP_Wst_CheckSumEmpTable @datetime, @TableName_SE output  
		
  
  set @TabSQL='insert into #Result select  fAccountID,fPurseID,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,'+
              'fConsCount,fConsMoney,fSaveCount,fSaveMoney,fTakeCount,fTakeMoney,fSubCount,fSubMoney,fClearCount,fClearMoney,fPutRightCount,fPutRightMoney,0,0,0,0,0,0,0,0,0,0,0,0 from '+
      @TableName_SE+' where fDate='''+@curday+''' '+@Where  
	 print @TabSQL
		EXEC(@TabSQL) 
		
		 set @TabSQL='insert into #Result select  fAccountID,fPurseID,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,'+
              '0,0,0,0,0,0,0,0,0,0,0,0,fConsCount,fConsMoney,fSaveCount,fSaveMoney,fTakeCount,fTakeMoney,fSubCount,fSubMoney,fClearCount,fClearMoney,fPutRightCount,fPutRightMoney from '+
      @TableName_SE+' where fDate>='''+@sDateBegin+''' AND fDate<'''+@sDateEnd+''' '+@Where  
	 print @TabSQL
		EXEC(@TabSQL)
			
  
  SELECT fAccountID,fPurseID,      
      sum(famount1) AS famount1, sum(fcount1) AS fcount1,               --餐次1消费金额，餐次1消费次数 
      sum(famount2) AS famount2, sum(fcount2) AS fcount2,               --餐次2消费金额，餐次2消费次数   
      sum(famount3) AS famount3, sum(fcount3) AS fcount3,               --餐次3消费金额，餐次3消费次数 
      sum(famount4) AS famount4, sum(fcount4) AS fcount4,               --餐次4消费金额，餐次4消费次数   
      sum(famount5) AS famount5, sum(fcount5) AS fcount5,               --餐次5消费金额，餐次5消费次数 
      sum(famount6) AS famount6, sum(fcount6) AS fcount6,               --餐次6消费金额，餐次6消费次数 
      sum(famount7) AS famount7, sum(fcount7) AS fcount7,               --餐次7消费金额，餐次7消费次数  
      sum(famount8) AS famount8, sum(fcount8) AS fcount8,               --餐次8消费金额，餐次8消费次数   
      sum(famountlimit1) AS famountlimit1,   sum(fcountlimit1) AS fcountlimit1, --餐次1限额消费金额，餐次1限额消费次数 
      sum(famountlimit2) AS famountlimit2,   sum(fcountlimit2) AS fcountlimit2, --餐次2限额消费金额，餐次2限额消费次数    
      sum(famountlimit3) AS famountlimit3,   sum(fcountlimit3) AS fcountlimit3, --餐次3限额消费金额，餐次3限额消费次数 
      sum(famountlimit4) AS famountlimit4,   sum(fcountlimit4) AS fcountlimit4, --餐次4限额消费金额，餐次4限额消费次数      
      sum(famountlimit5) AS famountlimit5,   sum(fcountlimit5) AS fcountlimit5, --餐次5限额消费金额，餐次5限额消费次数      
      sum(famountlimit6) AS famountlimit6,   sum(fcountlimit6) AS fcountlimit6, --餐次6限额消费金额，餐次6限额消费次数  
      sum(famountlimit7) AS famountlimit7,   sum(fcountlimit7) AS fcountlimit7, --餐次7限额消费金额，餐次7限额消费次数     
      sum(famountlimit8) AS famountlimit8,   sum(fcountlimit8) AS fcountlimit8, --餐次8限额消费金额，餐次8限额消费次数 
      sum(fConsCountD)   as fConsCountD,     sum(fConsMoneyD) as fConsMoneyD,              --消费按天汇总
      sum(fSaveCountD)   as fSaveCountD,     sum(fSaveMoneyD) as fSaveMoneyD,              --存款按天汇总
      sum(fTakeCountD)   as fTakeCountD,     sum(fTakeMoneyD) as fTakeMoneyD,              --取款按天汇总
      sum(fSubCountD)    as fSubCountD,      sum(fSubMoneyD) as fSubMoneyD,                --补助按天汇总
      sum(fClearCountD)  as fClearCountD,    sum(fClearMoneyD) as fClearMoneyD,            --补助清除按天汇总
      sum(fPutRightCountD) as fPutRightCountD,  sum(fPutRightMoneyD) as fPutRightMoneyD,   --纠错按天汇总
      sum(fConsCountM)   as fConsCountM,     sum(fConsMoneyM) as fConsMoneyM,              --消费按天汇总
      sum(fSaveCountM)   as fSaveCountM,     sum(fSaveMoneyM) as fSaveMoneyM,              --存款按天汇总
      sum(fTakeCountM)   as fTakeCountM,     sum(fTakeMoneyM) as fTakeMoneyM,              --取款按天汇总
      sum(fSubCountM)    as fSubCountM,      sum(fSubMoneyM) as fSubMoneyM,                --补助按天汇总
      sum(fClearCountM)  as fClearCountM,    sum(fClearMoneyM) as fClearMoneyM,            --补助清除按天汇总
      sum(fPutRightCountM) as fPutRightCountM,  sum(fPutRightMoneyM) as fPutRightMoneyM   --纠错按天汇总
				
				
    FROM #Result group by fAccountID,fPurseID order by fAccountID,fPurseID
  
end
go
--PROC_EDIT_1 写流水存储过程修改UP_InsertOnLineRecord

if exists(select  * from sys.all_objects where name='UP_InsertOnLineRecord' and type='P')
drop procedure UP_InsertOnLineRecord
GO 
CREATE PROCEDURE [dbo].[UP_InsertOnLineRecord]          
  @PurseID INT,      --钱包编号        
  @FlowType INT,      --流水类型        
  @RecType INT,      --交易类型        
  @UserCardID VARCHAR(16),   --用户卡号(物理卡号/应用序列号)        
  @PosID INT,       --交易终端号        
  @CreateTime DATETIME,    --交易时间        
  @RecvTime DATETIME,     --入库时间        
  @Amount Numeric(18,2),    --交易额        
  @Discount Numeric(18,2),   --折扣额        
  @SourceID INT,      --来源        
  @TaskID INT,      --任务编号        
  @OperID INT,      --操作员编号         
  @Fee1 Numeric(18,2),    --其他费用1(手续费)        
  @Fee2 Numeric(18,2),    --其他费用2(卡费)        
  @Fee3 Numeric(18,2),    --其他费用3(押金)        
  @Fee4 Numeric(18,2),    --其他费用4(管理费)        
  @OffTranNo INT,      --卡脱机交易序号        
  @PosTranNo INT,      --终端联机交易序号         
  @PosOffTranNo INT,     --终端脱机交易序号        
  @fRecKey VARCHAR(200),    --数据校验Key值    
  @fExternalOrder VARCHAR(100),       
  @Ret int output         
AS        
BEGIN        
 /*常量定义(过程内值不可修改)*/        
 DECLARE        
  @WtCons INT = 0,   --联机消费         
  @WtSave INT = 1,   --存款        
  @WtTake INT = 2,   --取款        
  @WtSub  INT = 3,   --补助        
  @WtLoss INT = 4,   --挂失        
  @WtUnLoss INT = 5,   --解挂        
  @WtMake INT = 6,   --配卡/开卡/开户        
  @WtDel INT = 7,    --有卡撤户        
  @WtRecovery INT = 8,  --纠错        
  @WtChange INT = 9,   --换卡换卡        
  @WtReMake INT = 10,   --补卡补卡        
  @WtModify INT = 11,   --有卡变更        
  @WtLogin INT = 12,   --登陆        
  @WtLoginOut INT = 13,  --退出        
  @WtLoginOutErr INT = 14, --未正常退出        
  @WtRefreshBList INT = 15, --黑名单刷新        
  @WtResetPW INT = 16,  --改密码        
  @WtOfflineWater INT = 17, --脱机消费        
  @WtDelWater INT = 18,  --删除流水        
  @WtDelCons INT = 19,  --删除营业        
  @WtDelCashier INT = 20,  --删除出纳        
  @WtLossAuto INT = 21,  --自动挂失        
  @WtModifyNOCard INT = 22, --无卡变更        
  @WtFrozen INT = 23,   --人工冻结        
  @WtFrozenAuto  INT = 24, --自动冻结        
  @WtDelNOCard INT = 25,  --无卡撤户        
  @WtReissue INT = 26,  --补发卡        
  @WtUnFrozen INT = 27,  --解冻        
  @WtCreditForLoad INT = 28,  --圈存        
  @WtCreditForWrite INT = 29, --圈存补款/圈存补写卡        
  @WtDebitForLoad INT = 30,   --圈提        
  @WtPrivilege INT = 31,      --优惠        
  @WtCount INT = 32,          --计次        
  @WtInto INT = 33,           --转入        
  @WtOut INT = 34,            --转出        
  @WtDelAcc INT = 35,         --删除资料        
  @WtPinCard INT = 36,        --销卡        
  @WtSubClear INT = 37,       --补助清零          
  @WtAddCard  INT = 38,  --增加副卡        
  @WtDelCard  INT = 39,  --注销副卡        
  @WtEnabledPurse INT = 40, --启用钱包        
  @WtDisabledPurse INT = 41,  --停用钱包        
  @WtAllow INT = 90           --门禁授权        
 /*过程变量定义*/        
 DECLARE        
  @AccountID VARCHAR(18),        
  @StationID VARCHAR(2),   --工作站编号        
  @DeptCode VARCHAR(20),   --部门编号        
  @MealID VARCHAR(3),    --交易时段编号         
  @OldMoney Numeric(18,2),  --交易前余额        
  @Balance Numeric(18,2),   --交易后余额        
  @OLTransNo INT,     --联机交易次数        
  @SettleTime DATETIME,   --入账时间        
  @Fraptime DATETIME,    --结算时间        
  @CardState INT,     --卡片状态  
  @Card_State INT,     --账户状态       
  @iSucc INT,      --写预存流水状态         
  @ErrAccID VARCHAR(20),   --无效账号 默认由原来的01999999修改为00000000        
  @ErrCardID VARCHAR(20),   --无效逻辑卡号        
  @Record_ID VARCHAR(10),        
  @fPurseID varchar(20),
  @LimitCountEnabled bit,   --POS机是否限次    
  @LimitMoneyEnabled bit,   --POS机是否限额   
  @KhDate datetime,
  @fHaveKhWater int --是否有开户流水 
 /*临时变量定义*/        
 DECLARE         
  @PTime VARCHAR(100),        
  @bPrint BIT,
  @ExecResult int   /*执行结果临时保存，原因是 @@Error 结果只能被读取一次，第二次读取时状态为0 */
  --交易时间去掉毫秒部分 
 SET @CreateTime=DATEADD(ms, -DATEPART(ms, @CreateTime), @CreateTime)   
 SET @Ret = 0  --赋值返回值初始值         
 SET @bPRINT = 1  --是否显示调试信息（用于显示各个阶段耗时）         
 SET @ErrAccID = '00000000'        
 SET @ErrCardID = '00000000'           
 SET @CardState=0 
 set @Card_State=0    
 SET @SettleTime = GETDATE()  --联机流水以当前时间下账   
 SET @fHaveKhWater=0
 set @fPurseID=''      
 
 --根据卡号获取账户信息        
 /*        
 1.在卡表中查询 T_B_Cards        
 2.在账户卡历史表中查询 T_B_CardHis        
 */  
       
 --1.在卡表中查询卡号对应帐号        
 SELECT top 1 @AccountID=C.fAccountID,@CardState=fCardState,@Card_State=fCard_State,@DeptCode=E.fDept,@KhDate=E.fKh_Date,@fHaveKhWater=E.fHaveKhWater FROM T_B_Cards C LEFT JOIN T_B_Employee E ON E.fAccountID=C.fAccountID WHERE C.fSerialNo=@UserCardID         
 IF (@@rowcount=0)  --未查询到对应账户        
 BEGIN        
  IF @bPRINT = 1 --日志显示 0 不显示 1显示        
  BEGIN        
   PRINT '-----------从卡历史日志表查询账户信息T_B_CardHis--------------'        
   SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
  END        
  --2.在账户卡历史表中查询 T_B_CardHis       用物理卡号、流水时间去查找对应的账号     
  SELECT @AccountID = fAccountID,@DeptCode = fDept FROM T_B_CardHis WHERE fSerialNo = @UserCardID and @CreateTime >= fBeginTime and @CreateTime < fEndTime        
  IF @@rowcount=0         
  BEGIN        
   SET @AccountID=@ErrAccID    
  END  
  else
  begin
    select @fHaveKhWater=fHaveKhWater,@Card_State=fCard_State from T_B_Employee where fAccountID=@AccountID
    select @CardState=fCard_State from T_B_Employee where fAccountID=@AccountID     --解决换卡后，卡号对应不上，造成流水不上传；    
  end  
 END        
 

 IF @AccountID <> @ErrAccID        
 BEGIN        
  IF @bPRINT = 1 --日志显示 0 不显示 1显示        
  BEGIN        
   PRINT '-----------写卡历史记录表--------------'        
   SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
  END           
  IF @bPRINT = 1 --日志显示 0 不显示 1显示        
  BEGIN        
   PRINT 'EXEC SP_SETCardHis '+@AccountID+','+@UserCardID+','+@DeptCode+','+convert(varchar(10),@CreateTime,120)+','+cast(@RecType as varchar(3))        
   SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
  END         
  EXEC SP_SETCardHis @AccountID, @UserCardID,@DeptCode,@CreateTime,@RecType        
 END    
 

 IF @RecType IN (@WtMake)
   update T_B_Employee set fLastOperateTime=GETDATE(),fHaveKhWater=1 where fAccountID=@AccountID  
 ELSE
   update T_B_Employee set fLastOperateTime=GETDATE() where fAccountID=@AccountID 
   
 /*根据交易时间获取交易时段*/        
 SET @MealID = '001'
 SELECT @MealID=ISNULL(fMeal_Id, '001') FROM T_B_MealSet WHERE (CAST(fBegin_Time as time)<=CAST(@CreateTime as time)) AND (CAST(fEnd_Time as time)>=CAST(@CreateTime as time))        
       
 /*根据终端号来获取工作站号*/    
 SET @StationID = '01' 
 SELECT @StationID=SUBSTRING(fSiteID,1,2), @LimitCountEnabled=fLimitCountEnabled,@LimitMoneyEnabled=fLimitMoneyEnabled FROM T_B_Pos WHERE fPosID=@PosID        

 --在钱包应用表中查找钱包信息  
 set @fPurseID=@AccountID+RIGHT('00'+CAST(@PurseID as varchar(2)),2)      
 SELECT @OldMoney=ISNULL(fBalance,0), @OLTransNo=ISNULL(fTransNo+1,1) FROM T_B_Purses WHERE fPurseID=@fPurseID        
  
 IF @@ROWCOUNT=0         
 BEGIN        
  SET @OldMoney=0        
  SET @OLTransNo=1        
  PRINT '----*****----'        
  PRINT @OldMoney        
  PRINT @OLTransNo        
  PRINT '----*****----'        
 END  
   --脱机流水的联机交易序号为0
 IF @RecType  IN (@WtOfflineWater) 
 BEGIN
   SET @PosTranNo=0
 END      
 /*根据交易额，交易前余额，手续费来计算交易后余额*/         
 IF @RecType in (@WtCons, @WtTake, @WtLoss, @WtUnLoss, @WtChange, @WtReMake, @WtModify,@WtOfflineWater, 
                 @WtReissue, @WtDebitForLoad, @WtPrivilege, @WtCount,@WtOut, @WtSubClear)         
 BEGIN        
  --余额减值交易        
  SET @Balance=@OldMoney-@Amount-@Fee1-@Fee2-@Fee4        
 END        
 ELSE IF @RecType in (@WtSave, @WtSub, @WtMake, @WtRecovery, @WtCreditForLoad, @WtCreditForWrite, @WtInto, @WtAddCard, @WtEnabledPurse)         
 BEGIN             
  --余额增值交易        
  SET @Balance=@OldMoney+@Amount-@Fee1-@Fee2-@Fee3-@Fee4        
 END        
 ELSE IF @RecType in (@WtDel, @WtDelNoCard )        
 BEGIN        
  SET @Balance=@OldMoney-@Amount-@Fee1-@Fee2       
 END        
 ELSE IF @RecType in (@WtPinCard,@WtDelCard, @WtDisabledPurse )        
 BEGIN        
  SET @Balance=@OldMoney-@Amount-@Fee1        
 END       
 ELSE BEGIN        
  SET @Balance=@OldMoney+@Amount        
 END        
        
 
 DECLARE @TabSQL_Over nVARCHAR(4000) 
 --如果流水时间小于开户时间或卡片为撤户状态的卡，就保存在过期流水表里
 if ( @AccountID = @ErrAccID ) OR  ((@CreateTime<@KhDate)or ((@Card_State=4) and (@RecType not IN (@WtDel, @WtDelNoCard ) )))  
 begin
   SET @TabSQL_Over=        
   'INSERT INTO [T_C_Rec_OverdueRec]         
    (fAccountID,        
    fSerialNo,        
    fPurseID,        
    fRecType,        
    fPosID,        
    fCreateTime,        
    fRecvTime,        
    fAmount,        
    fDiscount,        
    fSourceID,        
    fCardTranNo,            
    fPosTranNo,        
    fMealID,        
    fRecKey,  
    fExternalOrder)         
    VALUES(         
    ''' + @AccountID + ''',         
    ''' + @UserCardID + ''',         
    ' +  CAST(@PurseID AS VARCHAR(4)) + ',         
    ''' + CAST(@RecType AS VARCHAR(2)) + ''',         
    ''' + CAST(@PosID AS VARCHAR(5)) + ''',         
    ''' + CONVERT(VARCHAR(40), @CreateTime, 21) + ''',         
    ''' + CONVERT(VARCHAR(40), @RecvTime, 21) + ''',         
    ' +CAST(@Amount AS VARCHAR(18)) + ',         
    '+ CAST(@Discount AS VARCHAR(18)) + ',         
    ''' + CAST(@SourceID AS VARCHAR(3)) + ''',         
    ''' + CAST(@OffTranNo AS VARCHAR(10)) + ''',             
    ''' + CAST(@PosOffTranNo AS VARCHAR(10)) + ''',         
    ''' + @MealID  + ''',         
    ''' + @fRecKey + ''',  
    '''+ @fExternalOrder+''' ) '         
			EXEC sp_executesql @TabSQL_Over        
			IF @@ERROR <> 0                   
				SET @Ret = '2'          
			ELSE       
				SET @Ret = '0'         
			return     
 end
 
 --如果传上来的流水对应的账号是未开卡状态，就先保存在一张临时待处理表，当开卡流水上来后再处理
 if (@AccountID <> @ErrAccID ) and ( @RecType in (@WtCons,@WtSave,@WtTake,@WtSub,@WtLoss,@WtUnLoss,@WtDel,@WtRecovery,@WtChange,@WtReMake,
     @WtOfflineWater,@WtDelNOCard,@WtCreditForLoad,@WtCreditForWrite,@WtDebitForLoad,@WtPrivilege,@WtCount,@WtInto,@WtOut,@WtPinCard,@WtSubClear))
     and (@fHaveKhWater=0)    
 begin
  --待处理流水 
				insert into T_C_PendingConsRec(fPurseID,fFlowType,fRecType, fUserCardID,fPosID,fCreateTime,fRecvTime,fAmount,fDiscount,fSourceID,       
																																		fTaskID,fOperID,fFee1,fFee2,fFee3,fFee4,fOffTranNo,fPosTranNo,fPosOffTranNo,ffRecKey,ffExternalOrder)
				values(@PurseID,@flowType,@RecType, @UserCardID,@PosID,@CreateTime,@RecvTime,@Amount,@Discount,@SourceID,       
																																		@TaskID,@OperID,@fee1,@fee2,@fee3,@fee4,@OffTranNo,@PosTranNo,@PosOffTranNo,@fRecKey,@fExternalOrder)
			--如果写入第2步出错，就返回错误，让一卡通重新写流水
			IF @@ERROR <> 0                  
						SET @Ret = '2'         
			else        
			 		SET @Ret = '0'         
			return 					                           
 end
        
 IF @bPrint = 1        
 BEGIN        
  PRINT '-----------创建流水表--------------'        
  SELECT @Ptime = CONVERT(varchar(100), GETDATE(), 13)  print @Ptime        
 END        
 DECLARE @TableName_C varchar(30)         
 DECLARE @TableName_S varchar(30)
 DECLARE @TableName_W varchar(30)        
 /*检查或创建流水表*/        
 EXEC SP_Wst_CheckRecTable @CreateTime,0,  @TableName_C output
 EXEC SP_Wst_CheckRecTable @SettleTime,1,  @TableName_S output
 EXEC SP_Wst_CheckRecTable @CreateTime,2,  @TableName_W output
        
 /*记录还原点*/        
 BEGIN TRAN        
 IF @bPrint = 1        
 BEGIN        
  PRINT '-----------获取最大编号------------'        
  SELECT @Ptime = CONVERT(varchar(100), GETDATE(), 13)  print @Ptime         
 END          
 DECLARE @MaxID bigint        
 EXEC SP_Wst_GetRecMax @MaxID output        
 IF @MaxID <= 0 --如果取得的流水最大序号小于或等于0，表明最大序号获取有问题，直接返回执行存储过程错误        
 BEGIN        
  SET @Ret = '2'        
  GOTO returnErr        
 END        
         
 DECLARE @TabSQL nVARCHAR(4000)         
 IF @FlowType=1        
 BEGIN          
  IF @bPRINT = 1        
  BEGIN        
   PRINT '-----------插入未确认流水------------'        
   SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
  END          
  SET @TabSQL=        
   'INSERT INTO [T_C_Rec_Unconfirmed]         
    (fAccountID,        
    fSerialNo,        
    fPurseID,        
    fRecType,        
    fPosID,        
    fCreateTime,        
    fRecvTime,        
    fAmount,        
    fDiscount,        
    fSourceID,        
    fCardTranNo,            
    fPosTranNo,        
    fMealID,        
    fRecKey,  
    fExternalOrder)         
    VALUES(         
    ''' + @AccountID + ''',         
    ''' + @UserCardID + ''',         
    ' +  CAST(@PurseID AS VARCHAR(4)) + ',         
 ''' + CAST(@RecType AS VARCHAR(2)) + ''',         
    ''' + CAST(@PosID AS VARCHAR(5)) + ''',         
    ''' + CONVERT(VARCHAR(40), @CreateTime, 21) + ''',         
    ''' + CONVERT(VARCHAR(40), @RecvTime, 21) + ''',         
    ' +CAST(@Amount AS VARCHAR(18)) + ',         
    '+ CAST(@Discount AS VARCHAR(18)) + ',         
    ''' + CAST(@SourceID AS VARCHAR(3)) + ''',         
    ''' + CAST(@OffTranNo AS VARCHAR(10)) + ''',             
    ''' + CAST(@PosOffTranNo AS VARCHAR(10)) + ''',         
    ''' + @MealID  + ''',         
    ''' + @fRecKey + ''',  
    '''+ @fExternalOrder+''' ) '         
  EXEC sp_executesql @TabSQL        
  IF @@ERROR <> 0            
  BEGIN         
				SET @Ret = '2'        
				GOTO returnErr        
  END        
  ELSE BEGIN        
				SET @Ret = '0'         
				GOTO returnCommit        
  END          
 END        
 ELSE BEGIN         
  /*        
    流水按月分表存储，判断重复由表的联合主键判断        
    */                     
  --脱机流水需要判断是否重复
  IF @RecType IN (@WtOfflineWater) 
  begin
     DECLARE @FlowShaString varchar(200)
					set @FlowShaString=@AccountID+'_'+@UserCardID+'_'+CAST(@PurseID AS VARCHAR(4))+'_'+CAST(@RecType AS VARCHAR(2))+'_'+
																								CAST(@PosID AS VARCHAR(5))+'_'+CAST(@PosOffTranNo AS VARCHAR(10))+'_'+CAST(@Amount AS VARCHAR(18))
					set @FlowShaString=substring(sys.fn_varbintohexstr(hashbytes('SHA', @FlowShaString)),3,40)
     declare @iFlowCount int 
     SET @TabSQL='SELECT  @iFlowCount=count(*) FROM '+@TableName_W+' WHERE fShaValue='''+@FlowShaString+''''
     EXEC sp_executesql @TabSQL, N'@iFlowCount int output', @iFlowCount output
     IF @iFlowCount=0 
     BEGIN
        SET @TabSQL='INSERT INTO '+@TableName_W+'(fFlowType,fShaValue,fCreateTime) values('+CAST(@WtOfflineWater as varchar(2))+','''+@FlowShaString+''',GETDATE())'  
        PRINT @TabSQL
        EXEC sp_executesql @TabSQL 
          IF @@ERROR <> 0            
										BEGIN         
												SET @Ret = '2'        
												GOTO returnErr        
										END        
     END
     else
     begin
     --重复流水          
 				insert into T_C_REC_Repeat(fPurseID,fFlowType,fRecType,fUserCardID,fPosID,fCreateTime,fRecvTime,fAmount,fDiscount,
															fSourceID,fTaskID,fOperID,fFee1,fFee2,fFee3,fFee4,fOffTranNo,fPosTranNo,fPosOffTranNo,ffRecKey,ffExternalOrder)
						select   @PurseID,@FlowType,@RecType,@UserCardID,@PosID,@CreateTime,@RecvTime,@Amount,@Discount,@SourceID,
															@TaskID,@OperID,@Fee1,@Fee2,@Fee3,@Fee4,@OffTranNo,@PosTranNo,@PosOffTranNo,@fRecKey,@fExternalOrder
							IF @@ERROR <> 0
							BEGIN                          
						   	SET @Ret = '3'
						   	GOTO returnCommit
						 END
						 else
						 begin
						   SET @Ret = '0'
						   GOTO returnCommit 
						 end   
     end
  end 
  
  IF @bPRINT = 1        
  BEGIN        
   PRINT '-----------判断重复插入流水_C------------'        
   SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
  END   

  SET @TabSQL=        
   'INSERT INTO ['+@TableName_C+']         
    (fKeyID,        
    fAccountID,        
    fSerialNo,        
    fPurseID,        
    fRecType,        
    fCreateTime,        
    fRecvTime,        
    fSettleTime,        
    fOldBalance,        
    fAmount,        
    fNewBalance,        
    fFee1,        
    fFee2,        
    fFee3,        
    fFee4,        
    fDiscount,        
    fSourceID,        
    fPurseTranNo,        
    fCardTranNo,        
    fPosID,        
    fPosTranNo,        
    fPosOffTranNo,        
    fSiteID,        
    fDeptCode,        
    fOperID,        
    fMealID,        
    fTaskID,        
    fRecKey,  
    fExternalOrder)         
    VALUES(         
    ''' + CAST(@MaxID AS VARCHAR(30)) + ''',         
    ''' + @AccountID + ''',         
    ''' + @UserCardID + ''',         
    ' +  CAST(@PurseID AS VARCHAR(4)) + ',         
    ''' +CAST(@RecType AS VARCHAR(2)) + ''',         
    ''' + CONVERT(VARCHAR(40), @CreateTime, 21) + ''',         
    ''' + CONVERT(VARCHAR(40), @RecvTime, 21) + ''',         
    ''' + CONVERT(VARCHAR(40), @SETtletime, 21) + ''',         
    ' + CAST(@OldMoney AS VARCHAR(18))  + ',         
    ' + CAST(@Amount AS VARCHAR(18)) + ',         
    ' + CAST(@Balance AS VARCHAR(18)) + ',         
    ' + CAST(@Fee1 AS VARCHAR(18)) + ',         
    ' + CAST(@Fee2 AS VARCHAR(18)) + ',         
    ' + CAST(@Fee3 AS VARCHAR(18)) + ',         
    ' + CAST(@Fee4 AS VARCHAR(18)) + ',         
    ' + CAST(@Discount AS VARCHAR(18)) + ',         
    ''' +  CAST(@SourceID AS VARCHAR(3)) + ''',										
    ''' +  CAST(@OLTransNo AS VARCHAR(10)) + ''',         
    ''' + CAST(@OffTranNo AS VARCHAR(10)) + ''',         
    ''' + CAST(@PosID AS VARCHAR(5)) + ''',         
    ''' +  CAST(@PosTranNo AS VARCHAR(10)) + ''',         
    ''' +  CAST(@PosOffTranNo AS VARCHAR(10)) + ''',         
    ''' +  @Stationid + ''',         
    ''' + @DeptCode + ''',         
    ''' + CAST(@OperID AS VARCHAR(5)) + ''',          
    ''' + @MealID  + ''',         
    ' + CAST(@TaskID AS VARCHAR(5))+ ',         
    ''' + @fRecKey + ''' ,  
    '''+@fExternalOrder+''' ) '         
  IF @bPRINT = 1        
  BEGIN    
   PRINT '1 ' + CAST(@MaxID AS VARCHAR(30))        
   PRINT '2 ' +  @AccountID         
   PRINT '3 ' +  @UserCardID         
   PRINT '4 ' + CAST(@PurseID AS VARCHAR(4))         
   PRINT '5 ' + CAST(@RecType AS VARCHAR(2))         
   PRINT '6 ' + CONVERT(VARCHAR(40), @CreateTime, 21)        
   PRINT '7 ' + CONVERT(VARCHAR(40), @RecvTime, 21)         
   PRINT '8 ' + CONVERT(VARCHAR(40), @SETtletime, 21)          
   PRINT '9 ' + CAST(@OldMoney AS VARCHAR(18))         
   PRINT '10 ' + CAST(@Amount AS VARCHAR(18))         
   PRINT '11 ' + CAST(@Balance AS VARCHAR(18))        
   PRINT '12 ' + CAST(@Fee1 AS VARCHAR(18))         
   PRINT '13 ' + CAST(@Fee2 AS VARCHAR(18))         
   PRINT '14 ' + CAST(@Fee3 AS VARCHAR(18))         
   PRINT '15 ' + CAST(@Fee4 AS VARCHAR(18))         
   PRINT '16 ' + CAST(@OLTransNo AS VARCHAR(10))         
   PRINT '17 ' + CAST(@OffTranNo AS VARCHAR(10))         
   PRINT '18 ' + CAST(@PosID AS VARCHAR(5))         
   PRINT '19 ' + CAST(@PosTranNo AS VARCHAR(10))        
   PRINT '20 ' + @Stationid         
   PRINT '21 ' + @DeptCode         
   PRINT '22 ' + CAST(@OperID AS VARCHAR(5))             
   PRINT '23 ' + @MealID           
   PRINT '24 ' + @fRecKey         
   PRINT '25 ' + CAST(@SourceID AS VARCHAR(5))          
            
   PRINT @TabSQL        
   SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
  END         
  EXEC sp_executesql @TabSQL  
  set @ExecResult = @@ERROR      
  IF @ExecResult <> 0            
  BEGIN                     
	IF @ExecResult = 2627 
	BEGIN    
	   --重复流水 
  	  insert into T_C_REC_Repeat(fPurseID,fFlowType,fRecType,fUserCardID,fPosID,fCreateTime,fRecvTime,fAmount,fDiscount,
								 fSourceID,fTaskID,fOperID,fFee1,fFee2,fFee3,fFee4,fOffTranNo,fPosTranNo,fPosOffTranNo,ffRecKey,ffExternalOrder)
						 select  @PurseID,@FlowType,@RecType,@UserCardID,@PosID,@CreateTime,@RecvTime,@Amount,@Discount,@SourceID,
								 @TaskID,@OperID,@Fee1,@Fee2,@Fee3,@Fee4,@OffTranNo,@PosTranNo,@PosOffTranNo,@fRecKey,@fExternalOrder                      
	  SET @Ret = '3'
	  GOTO returnCommit
    END
    else   
	BEGIN         
		SET @Ret = '2'        
		GOTO returnErr        
	END 
  END
    

  IF @bPRINT = 1        
  BEGIN        
   PRINT '-----------判断重复插入流水_S------------'        
   SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
  END           
  SET @TabSQL=        
			   'INSERT INTO ['+@TableName_S+']         
				(fKeyID,        
				fAccountID,        
				fSerialNo,        
				fPurseID,        
				fRecType,        
				fCreateTime,        
				fRecvTime,        
				fSettleTime,        
				fOldBalance,        
				fAmount,        
				fNewBalance,        
				fFee1,        
				fFee2,        
				fFee3,        
				fFee4,        
				fDiscount,        
				fSourceID,        
				fPurseTranNo,        
				fCardTranNo,        
				fPosID,        
				fPosTranNo,        
				fPosOffTranNo,        
				fSiteID,        
				fDeptCode,        
				fOperID,        
				fMealID,        
				fTaskID,        
				fRecKey,  
				fExternalOrder)         
				VALUES(         
				''' + CAST(@MaxID AS VARCHAR(30)) + ''',         
				''' + @AccountID + ''',         
				''' + @UserCardID + ''',         
				' +  CAST(@PurseID AS VARCHAR(4)) + ',         
				''' +CAST(@RecType AS VARCHAR(2)) + ''',         
				''' + CONVERT(VARCHAR(40), @CreateTime, 21) + ''',         
				''' + CONVERT(VARCHAR(40), @RecvTime, 21) + ''',         
				''' + CONVERT(VARCHAR(40), @SETtletime, 21) + ''',         
				' + CAST(@OldMoney AS VARCHAR(18))  + ',         
				' + CAST(@Amount AS VARCHAR(18)) + ',         
				' + CAST(@Balance AS VARCHAR(18)) + ',         
				' + CAST(@Fee1 AS VARCHAR(18)) + ',         
				' + CAST(@Fee2 AS VARCHAR(18)) + ',         
				' + CAST(@Fee3 AS VARCHAR(18)) + ',         
				' + CAST(@Fee4 AS VARCHAR(18)) + ',         
				' + CAST(@Discount AS VARCHAR(18)) + ',         
				''' +  CAST(@SourceID AS VARCHAR(3)) + ''',         
				''' +  CAST(@OLTransNo AS VARCHAR(10)) + ''',         
				''' + CAST(@OffTranNo AS VARCHAR(10)) + ''',         
				''' + CAST(@PosID AS VARCHAR(5)) + ''',         
				''' +  CAST(@PosTranNo AS VARCHAR(10)) + ''',         
				''' +  CAST(@PosOffTranNo AS VARCHAR(10)) + ''',         
				''' +  @Stationid + ''',         
				''' + @DeptCode + ''',         
				''' + CAST(@OperID AS VARCHAR(5)) + ''',          
				''' + @MealID  + ''',         
				' + CAST(@TaskID AS VARCHAR(5))+ ',         
				''' + @fRecKey + ''' ,  
				'''+@fExternalOrder+''' ) '         
  IF @bPRINT = 1        
  BEGIN        
           
   PRINT '1 ' + CAST(@MaxID AS VARCHAR(30))        
   PRINT '2 ' +  @AccountID         
  PRINT '3 ' +  @UserCardID         
   PRINT '4 ' + CAST(@PurseID AS VARCHAR(4))         
   PRINT '5 ' + CAST(@RecType AS VARCHAR(2))         
   PRINT '6 ' + CONVERT(VARCHAR(40), @CreateTime, 21)        
   PRINT '7 ' + CONVERT(VARCHAR(40), @RecvTime, 21)         
   PRINT '8 ' + CONVERT(VARCHAR(40), @SETtletime, 21)          
   PRINT '9 ' + CAST(@OldMoney AS VARCHAR(18))         
   PRINT '10 ' + CAST(@Amount AS VARCHAR(18))         
   PRINT '11 ' + CAST(@Balance AS VARCHAR(18))        
   PRINT '12 ' + CAST(@Fee1 AS VARCHAR(18))         
   PRINT '13 ' + CAST(@Fee2 AS VARCHAR(18))         
   PRINT '14 ' + CAST(@Fee3 AS VARCHAR(18))         
   PRINT '15 ' + CAST(@Fee4 AS VARCHAR(18))         
   PRINT '16 ' + CAST(@OLTransNo AS VARCHAR(10))         
   PRINT '17 ' + CAST(@OffTranNo AS VARCHAR(10))         
   PRINT '18 ' + CAST(@PosID AS VARCHAR(5))         
   PRINT '19 ' + CAST(@PosTranNo AS VARCHAR(10))        
   PRINT '20 ' + @Stationid         
   PRINT '21 ' + @DeptCode         
   PRINT '22 ' + CAST(@OperID AS VARCHAR(5))             
   PRINT '23 ' + @MealID           
   PRINT '24 ' + @fRecKey         
   PRINT '25 ' + CAST(@SourceID AS VARCHAR(5))          
            
   PRINT @TabSQL        
   SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
  END         
  EXEC sp_executesql @TabSQL
  set @ExecResult = @@ERROR 
  IF @ExecResult <> 0            
  BEGIN                     
	IF @ExecResult = 2627 
	BEGIN    
	   --重复流水 
  	  insert into T_C_REC_Repeat(fPurseID,fFlowType,fRecType,fUserCardID,fPosID,fCreateTime,fRecvTime,fAmount,fDiscount,
								 fSourceID,fTaskID,fOperID,fFee1,fFee2,fFee3,fFee4,fOffTranNo,fPosTranNo,fPosOffTranNo,ffRecKey,ffExternalOrder)
					     select  @PurseID,@FlowType,@RecType,@UserCardID,@PosID,@CreateTime,@RecvTime,@Amount,@Discount,@SourceID,
								 @TaskID,@OperID,@Fee1,@Fee2,@Fee3,@Fee4,@OffTranNo,@PosTranNo,@PosOffTranNo,@fRecKey,@fExternalOrder                      
	  SET @Ret = '3'
	  GOTO returnCommit
    END
    else   
	BEGIN         
		SET @Ret = '2'        
		GOTO returnErr        
	END 
  END 
END   
         
 --更新账户信息        
 IF @bPRINT = 1        
 BEGIN         
  PRINT '-----------更新账户信息------------'        
  SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime        
 END          
 IF @AccountID <> @ErrAccID --当流水为有效账户流水时才对账户进行数据更新        
 BEGIN        
  IF @RecType in (@WtCons,@WtSave,@WtTake,@WtSub,@WtLoss,@WtUnLoss,@WtMake,@WtDel,@WtRecovery,@WtChange,        
      @WtReMake,@WtOfflineWater,@WtDelNOCard,@WtCreditForLoad,@WtDebitForLoad,@WtInto,@WtOut,@WtEnabledPurse,        
      @WtSubClear,@WtAddCard)  --正常交易类数据更新        
  BEGIN           
     UPDATE T_B_Purses SET fBalance = @Balance,fTransNo = @OLTransNo  WHERE fPurseID=@fPurseID 
     IF @@ERROR <> 0            
	 BEGIN         
		SET @Ret = '2'        
		GOTO returnErr        
	 END     
  END        
 END        
 IF  @RecType = @WtMake   
 BEGIN
    UPDATE T_B_Employee SET fCard_State=0,fSerialNo=@UserCardID WHERE fAccountID=@AccountID
    IF @@ERROR <> 0            
	BEGIN         
	  SET @Ret = '2'        
	  GOTO returnErr        
	END 
 END     

  if @RecType in (@WtPinCard,@WtDelCard)
  begin
     DELETE FROM T_B_Cards WHERE fSerialID = @UserCardID
     IF @@ERROR <> 0            
  	 BEGIN         
	   SET @Ret = '2'        
	   GOTO returnErr        
  	 END      
     if @RecType  in (@WtPinCard)
	 begin
		if exists(select  * from (select  * from  T_B_Cards where fSerialNo=@UserCardID ) a left join (select * from T_B_CardType where fIsMainCard=1) b on a.fCardTypeID=b.fCardTypeID)            
		update T_B_Employee set fCard_State=2 where fAccountID=@AccountID
     end
     else
     begin
       update T_B_Employee set fCard_State=2 where fAccountID=@AccountID
     end
     IF @@ERROR <> 0            
 	 BEGIN         
	  SET @Ret = '2'        
	  GOTO returnErr        
 	 END 
  end   
  else if @RecType in (@WtDel,@WtDelNOCard)--如果是撤户的就需要删除卡表数据  
  begin
    delete from T_B_Cards where  fAccountID=@AccountID 
    IF @@ERROR <> 0            
 	BEGIN         
	  SET @Ret = '2'        
	  GOTO returnErr        
  	END        
    delete from T_B_Purses where fAccountID=@AccountID 
    IF @@ERROR <> 0            
	BEGIN         
	  SET @Ret = '2'        
	  GOTO returnErr        
  	END          
    update T_B_Employee set fCard_State=4,fSerialNo='' where fAccountID=@AccountID
    IF @@ERROR <> 0            
 	BEGIN         
	  SET @Ret = '2'        
	  GOTO returnErr        
  	END       
  end
  

   --汇总数据        
 DECLARE @sDate    VARCHAR(20)   --入账日期        
 DECLARE @fKey_SP  VARCHAR(30)    --T_C_SUM_Pos表的关键字        
 DECLARE @fKey_SO  VARCHAR(30)   --T_C_SUM_OPER表的关键字        
 DECLARE @fKey_SE  VARCHAR(30)   --T_C_SUMEmp表的关键字        
 DECLARE @fKey_CE  VARCHAR(30)   --T_C_CashEmp表的关键字         
 DECLARE @fKey_PDR VARCHAR(30)   --T_B_PosDayRecs表的关键字
 declare @Key_Week  VARCHAR(30)  --T_C_CashEmp表类型:周
 declare @Key_Month VARCHAR(30)  --T_C_CashEmp表类型:月
 declare @Key_Year  VARCHAR(30)  --T_C_CashEmp表类型:年
 declare @where_Week varchar(30)
 declare @where_Month varchar(30)
 declare @where_Year varchar(30)
   
 set @where_Week=right('00'+cast((datepart(wk,GETDATE()) - datepart(wk,convert(varchar(7),GETDATE(),120) + '-01') + 1) as varchar(2)),2)--当月第几周
 set @where_Month=right('00'+cast(MONTH(GETDATE()) as varchar(2)),2)--月份
 set @where_Year=cast(year(GETDATE()) as varchar(4))--年份
 set @where_Week=@where_Year+@where_Month+@where_Week
 set @where_Month=@where_Year+@where_Month+'00'
 set @where_Year=@where_Year+'0000'
 set @Key_Week='01'
 set @Key_Month='02'
 set @Key_Year='03'        
 SET @sDate = CONVERT(VARCHAR(20),@SettleTime,112) --格式 20131212        
 SET @fKey_SP  = @sDate + DBO.FN_FillZero(5, @PosID)  + @MealID + DBO.FN_FillZero(2, @PurseID)               
 SET @fKey_SO  = @sDate + DBO.FN_FillZero(5, @OperID) + @MealID + DBO.FN_FillZero(2, @PurseID)          
 SET @fKey_SE  = @sDate + DBO.FN_FillZero(8, @AccountID) + DBO.FN_FillZero(2, @PurseID)         
 SET @fKey_PDR = @sDate + DBO.FN_FillZero(5, @PosID ) + DBO.FN_FillZero(2, @PurseID)           
 SET @fKey_CE  = DBO.FN_FillZero(8, @AccountID) + DBO.FN_FillZero(2, @PurseID)+@sDate+@MealID    --账号+钱包号+日期+餐次   
 SET @sDate = CONVERT(VARCHAR(20),@SettleTime,23) --格式 2013-12-12        
 
  --汇总限次
  IF @RecType IN (@WtCons, @WtOfflineWater, @WtRecovery)         
 BEGIN        
  IF @bPRINT = 1        
  BEGIN        
   PRINT '-----------汇总数据5-更新用户每日餐次消费汇总信息------------'        
   SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime        
  END               
  DECLARE @WhereUp_CE VARCHAR(180)  
  DECLARE @WhereUp_CEC VARCHAR(180) 
  DECLARE @WhereUp_CEM VARCHAR(180)           
  DECLARE @WhereInValue_CE VARCHAR(180)   
  DECLARE @WhereInValue_CEC VARCHAR(180)
  DECLARE @WhereInValue_CEM VARCHAR(180)          
  DECLARE @Symbol VARCHAR(1) 
  
  IF @RecType=@WtRecovery
	SET @Symbol='-'
  ELSE
	SET @Symbol='+'
       
  set @WhereUp_CE=''
  set @WhereUp_CEC=''
  set @WhereUp_CEM=''
  set @WhereInValue_CE=''
  set @WhereInValue_CEC=''
  set @WhereInValue_CEM=''
  
  
  --如果限次功能开启
  if @LimitCountEnabled=1
  begin  
     if  @WhereUp_CEC='' 
        set @WhereUp_CEC='fcount=fcount'+@Symbol+' 1,fcountLimit=fcountLimit '+@Symbol+' 1 '
     else
        set @WhereUp_CEC=',fcount=fcount'+@Symbol+' 1,fcountLimit=fcountLimit '+@Symbol+' 1 '
     SET @WhereInValue_CEC = ',1,1 '
  end   
  else
  begin
     if  @WhereUp_CEC=''
        set @WhereUp_CEC='fcount=fcount'+@Symbol+' 1 '
     else 
        set @WhereUp_CEC=',fcount=fcount'+@Symbol+' 1 '
     SET @WhereInValue_CEC = ',1,0 '    
  end   
  
  --如果限额功能开启
  if @LimitMoneyEnabled=1
  BEGIN
     set @WhereUp_CEM=',famount=famount '+@Symbol+ CAST(@Amount AS VARCHAR(18))+',famountLimit =famountLimit '+@Symbol+ CAST(@Amount AS VARCHAR(18))
     SET @WhereInValue_CEM = ','+CAST(@Amount AS VARCHAR(18))+','+CAST(@Amount AS VARCHAR(18))
  END
  else
  begin
     set @WhereUp_CEM=',famount=famount '+@Symbol+ CAST(@Amount AS VARCHAR(18))
     SET @WhereInValue_CEM = ','+CAST(@Amount AS VARCHAR(18))+',0'    
  end
  
  set @WhereUp_CE=@WhereUp_CEC+@WhereUp_CEM
  SET @WhereInValue_CE=@WhereInValue_CEC+@WhereInValue_CEM
  SET @WhereUp_CE=ISNULL(@WhereUp_CE,'')              
  SET @WhereInValue_CE=ISNULL(@WhereInValue_CE,'') 
  SET @TabSQL='UPDATE [T_C_CashEmp] SET '+@WhereUp_CE+' WHERE fkey= ''' + CAST(@fKey_CE AS VARCHAR(30)) + ''''         
  
  IF @bPRINT = 1        
  BEGIN        
   PRINT @TabSQL        
   SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
  END   
  DECLARE @UpdateRecCount INT      
  EXEC sp_executesql @TabSQL      
  SET @UpdateRecCount=@@rowcount        
  IF @@ERROR <> 0            
  BEGIN         
   SET @Ret = '2'    
   GOTO returnErr         
  END          
  PRINT '@UpdateRecCount - '+CAST(@UpdateRecCount AS VARCHAR(1))        
  IF @UpdateRecCount = 0         
  BEGIN 
   --插入天汇总       
   SET @TabSQL=        
    'INSERT INTO [T_C_CashEmp]         
     (fkey,        
     faccountID,        
     fdate,        
     fpurseID,        
     fmealID,
     fcount,
     fcountLimit,
     famount,
     famountLimit)         
     VALUES(         
     ''' + @fKey_CE + ''', ''' +         
     @AccountID + ''', ''' +         
     @sDate + ''', ' +          
     CAST(@PurseID AS VARCHAR(4)) + ', ''' +  
     @MealID +''''+       
     @WhereInValue_CE + ') '          
   IF @bPRINT = 1        
   BEGIN         
    PRINT @TabSQL        
    SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
   END         
   EXEC sp_executesql @TabSQL         
   IF @@ERROR <> 0            
   BEGIN         
    SET @Ret = '2'         
    GOTO returnErr         
   END 
  
  end
  

  --更新周汇总
				SET @TabSQL='UPDATE [T_C_CashEmpEx] SET '+@WhereUp_CE+' WHERE fkey= ''' + @Key_Week+DBO.FN_FillZero(8, @AccountID) + DBO.FN_FillZero(2, @PurseID)+@where_Week+@MealID + ''''         
				IF @bPRINT = 1        
				BEGIN        
					PRINT @TabSQL        
					SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
				END   
				EXEC sp_executesql @TabSQL
				SET @UpdateRecCount=@@rowcount          
				IF @@ERROR <> 0            
				BEGIN         
						SET @Ret = '2'         
						GOTO returnErr            
				END
				
				if @UpdateRecCount=0
				begin
							--插入周汇总       
							SET @TabSQL=        
							'INSERT INTO [T_C_CashEmpEx]         
								(fkey, 
								ftype,       
								faccountID,        
								fvalue,        
								fpurseID,        
								fmealID,
								fcount,
								fcountLimit,
								famount,
								famountLimit)         
								VALUES(         
								''' + @Key_Week+DBO.FN_FillZero(8, @AccountID) + DBO.FN_FillZero(2, @PurseID)+@where_Week+@MealID + ''', ''' +  
								@Key_Week +''','''+      
								@AccountID + ''', ''' +         
								@where_Week + ''', ' +          
								CAST(@PurseID AS VARCHAR(4)) + ', ''' +  
								@MealID +  ''''+      
								@WhereInValue_CE + ') '          
						IF @bPRINT = 1        
						BEGIN         
							PRINT @TabSQL        
							SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
						END         
						EXEC sp_executesql @TabSQL         
						IF @@ERROR <> 0            
						BEGIN         
							SET @Ret = '2'         
							GOTO returnErr          
						END
				end
				
				--更新月汇总
				SET @TabSQL='UPDATE [T_C_CashEmpEx] SET '+@WhereUp_CE+' WHERE fkey= ''' + @Key_Month+DBO.FN_FillZero(8, @AccountID) + DBO.FN_FillZero(2, @PurseID)+@where_Month+@MealID + ''''         
				IF @bPRINT = 1        
				BEGIN        
					PRINT @TabSQL        
					SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
				END   
				EXEC sp_executesql @TabSQL 
				SET @UpdateRecCount=@@rowcount         
				IF @@ERROR <> 0            
				BEGIN         
						SET @Ret = '2'         
						GOTO returnErr          
				END
				
				if @UpdateRecCount=0
				begin
								--插入月汇总       
							SET @TabSQL=        
								'INSERT INTO [T_C_CashEmpEx]         
									(fkey, 
									ftype,       
									faccountID,        
									fvalue,        
									fpurseID,        
									fmealID,
									fcount,
									fcountLimit,
									famount,
									famountLimit)         
									VALUES(         
									''' + @Key_Month+DBO.FN_FillZero(8, @AccountID) + DBO.FN_FillZero(2, @PurseID)+@where_Month+@MealID + ''', ''' +  
									@Key_Month +''','''+      
									@AccountID + ''', ''' +         
									@where_Month + ''', ' +          
									CAST(@PurseID AS VARCHAR(4)) + ', ''' +  
									@MealID +  ''''+      
									@WhereInValue_CE + ') '          
							IF @bPRINT = 1        
							BEGIN         
								PRINT @TabSQL        
								SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
							END         
							EXEC sp_executesql @TabSQL         
							IF @@ERROR <> 0            
							BEGIN         
								SET @Ret = '2'         
								GOTO returnErr         
							END
				end
				
				--更新年汇总
				SET @TabSQL='UPDATE [T_C_CashEmpEx] SET '+@WhereUp_CE+' WHERE fkey= ''' + @Key_Year+DBO.FN_FillZero(8, @AccountID) + DBO.FN_FillZero(2, @PurseID)+@where_Year+@MealID + ''''         
				IF @bPRINT = 1        
				BEGIN        
					PRINT @TabSQL        
					SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
				END   
				EXEC sp_executesql @TabSQL 
				SET @UpdateRecCount=@@rowcount         
				IF @@ERROR <> 0            
				BEGIN         
						SET @Ret = '2'         
						GOTO returnErr           
				END
			 if @UpdateRecCount=0
				begin
							--插入年汇总       
							SET @TabSQL=        
								'INSERT INTO [T_C_CashEmpEx]         
									(fkey, 
									ftype,       
									faccountID,        
									fvalue,        
									fpurseID,        
									fmealID,
									fcount,
									fcountLimit,
									famount,
									famountLimit)         
									VALUES(         
									''' + @Key_Year+DBO.FN_FillZero(8, @AccountID) + DBO.FN_FillZero(2, @PurseID)+@where_Year+@MealID + ''', ''' +  
									@Key_Year +''','''+      
									@AccountID + ''', ''' +         
									@where_Year + ''', ' +          
									CAST(@PurseID AS VARCHAR(4)) + ', ''' +  
									@MealID +  ''''+      
									@WhereInValue_CE + ') '          
							IF @bPRINT = 1        
							BEGIN         
								PRINT @TabSQL        
								SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
							END         
							EXEC sp_executesql @TabSQL         
							IF @@ERROR <> 0            
							BEGIN         
								SET @Ret = '2'         
								GOTO returnErr            
							END   
     
  END  
  
 END 

if @RecType IN (@WtCons, @WtOfflineWater,@WtRecovery,@WtSave, @WtCreditForLoad, @WtInto, @WtMake,@WtTake, @WtDebitForLoad, @WtOut, @WtDel, @WtDelNOCard,@WtSub,@WtSubClear,@WtLoss,@WtUnLoss,@WtRecovery,@WtChange,@WtReMake,@WtLoss,@WtUnLoss,@WtRecovery,@WtChange,@WtReMake)         
 begin        
 IF @bPRINT = 1        
 BEGIN        
  PRINT '-----------汇总数据4-更新用户交易汇总信息------------'        
  SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime        
 END         
 DECLARE @TableName_SE VARCHAR(20)        
 DECLARE @WhereUp VARCHAR(400)        
 DECLARE @WhereInField VARCHAR(400)        
 DECLARE @WhereInValue VARCHAR(400)        
 EXEC SP_Wst_CheckSumEmpTable @RecvTime, @TableName_SE output        
 set @WhereUp=''        
 IF @RecType IN (@WtCons, @WtOfflineWater)         
 BEGIN        
   IF @Discount=0        
   BEGIN        
    SET @WhereUp = 'fConsCount = fConsCount + 1, fConsMoney = fConsMoney + ' + CAST(@Amount AS VARCHAR(18))  
    if @LimitCountEnabled=1    
        SET @WhereUp = @WhereUp+',fLimitConsCount = fLimitConsCount + 1, fLimitConsMoney = fLimitConsMoney + ' + CAST(@Amount AS VARCHAR(18))        
    SET @WhereInField = 'fConsCount, fConsMoney,fLimitConsCount, fLimitConsMoney'   
    if @LimitCountEnabled=1       
       SET @WhereInValue = '1, '+CAST(@Amount AS VARCHAR(18))+',1,'+ CAST(@Amount AS VARCHAR(18))+','  
    else  
       SET @WhereInValue = '1, '+CAST(@Amount AS VARCHAR(18))+',0,0,'          
   END        
   ELSE BEGIN        
    SET @WhereUp = 'fConsCount = fConsCount + 1, fConsMoney = fConsMoney + ' + CAST(@Amount AS VARCHAR(18)) +        
        ',fDiscountCount = fDiscountCount + 1, fDiscountMoney = fDiscountMoney + ' + CAST(@Discount AS VARCHAR(18))   
    if @LimitCountEnabled=1    
       SET @WhereUp = @WhereUp+',fLimitConsCount = fLimitConsCount + 1, fLimitConsMoney = fLimitConsMoney + ' + CAST(@Amount AS VARCHAR(18))            
    SET @WhereInField = 'fConsCount, fConsMoney, fDiscountCount, fDiscountMoney,fLimitConsCount, fLimitConsMoney'  
    if @LimitCountEnabled=1        
       SET @WhereInValue = '1, '+CAST(@Amount AS VARCHAR(18))+',1, '+CAST(@Discount AS VARCHAR(18))+',1,'+ CAST(@Amount AS VARCHAR(18))+','  
    else  
       SET @WhereInValue = '1, '+CAST(@Amount AS VARCHAR(18))+',1, '+CAST(@Discount AS VARCHAR(18))+',0,0,'             
   END        
 END        
 ELSE IF @RecType IN (@WtRecovery)         
 BEGIN        
  SET @WhereUp = 'fPutRightCount = fPutRightCount + 1, fPutRightMoney = fPutRightMoney + ' + CAST(@Amount AS VARCHAR(18))         
  SET @WhereInField = 'fPutRightCount, fPutRightMoney'        
  SET @WhereInValue = '1, '+CAST(@Amount AS VARCHAR(18))+','        
 END        
 ELSE IF @RecType IN (@WtSave, @WtCreditForLoad, @WtInto, @WtMake)        
 BEGIN        
  SET @WhereUp = 'fSaveCount = fSaveCount + 1, fSaveMoney = fSaveMoney + ' + CAST(@Amount AS VARCHAR(18))         
  SET @WhereInField = 'fSaveCount, fSaveMoney'        
  SET @WhereInValue = '1, '+CAST(@Amount AS VARCHAR(18))+','        
 END IF @RecType IN (@WtTake, @WtDebitForLoad, @WtOut, @WtDel, @WtDelNOCard,@WtLoss,@WtUnLoss,@WtRecovery,@WtChange,@WtReMake)        
 BEGIN        
  SET @WhereUp = 'fTakeCount = fTakeCount + 1, fTakeMoney = fTakeMoney + ' + CAST(@Amount AS VARCHAR(18))         
  SET @WhereInField = 'fTakeCount, fTakeMoney'        
  SET @WhereInValue = '1, '+CAST(@Amount AS VARCHAR(18))+','        
 END IF @RecType IN (@WtSub)        
 BEGIN        
  SET @WhereUp = 'fSubCount = fSubCount + 1, fSubMoney = fSubMoney + ' + CAST(@Amount AS VARCHAR(18))         
  SET @WhereInField = 'fSubCount, fSubMoney'        
  SET @WhereInValue = '1, '+CAST(@Amount AS VARCHAR(18))+','        
 END IF @RecType IN (@WtSubClear)        
 BEGIN        
  SET @WhereUp = 'fClearCount = fClearCount + 1, fClearMoney = fClearMoney + ' + CAST(@Amount AS VARCHAR(18))         
  SET @WhereInField = 'fClearCount, fClearMoney'        
  SET @WhereInValue = '1, '+CAST(@Amount AS VARCHAR(18))+','        
 END        
          
 SET @WhereUp=ISNULL(@WhereUp,'')        
 SET @WhereInField=ISNULL(@WhereInField,'')        
 SET @WhereInValue=ISNULL(@WhereInValue,'')        
         
 /*        
 IF @bPRINT = 1        
 BEGIN        
  PRINT @TabSQL        
  SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
 END         
 EXEC sp_executesql @TabSQL         
 IF @@ERROR <> 0            
 BEGIN         
  SET @Ret = '3'         
  GOTO returnCommit         
 END         
 */        
 if @WhereUp=''      
 set @WhereUp=' fOldBalance=fOldBalance+0 '      
 SET @TabSQL=        
  'UPDATE a          
  SET '+@WhereUp+ ', ' +         
   'fFee1 = fFee1 + '+CAST(@Fee1 AS VARCHAR(18)) + ', ' +         
   'fFee2 = fFee2 + '+CAST(@Fee2 AS VARCHAR(18)) + ', ' +         
   'fFee3 = fFee3 + '+CAST(@Fee3 AS VARCHAR(18)) + ', ' +         
   'fFee4 = fFee4 + '+CAST(@Fee4 AS VARCHAR(18)) + ', ' +         
   'a.fNewBalance = b.fBalance'+ 
   ' from ['+@TableName_SE+'] a  '+ 
   ' LEFT JOIN T_B_Purses b on a.fAccountID=b.fAccountID and b.fPurseCode='+CAST(@PurseID as varchar(10))+      
   ' WHERE fKeyID= ''' + CAST(@fKey_SE AS VARCHAR(30)) + ''''         
 IF @bPRINT = 1        
 BEGIN        
  PRINT @TabSQL        
  SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
 END         
 EXEC sp_executesql @TabSQL               
 SET @UpdateRecCount=@@rowcount        
 IF @@ERROR <> 0            
 BEGIN         
  SET @Ret = '2'         
  GOTO returnErr         
 END          
 PRINT '@UpdateRecCount - '+CAST(@UpdateRecCount AS VARCHAR(1))        
 IF @UpdateRecCount = 0         
 BEGIN        
  SET @TabSQL=        
   'INSERT INTO ['+@TableName_SE+']         
    (fKeyID,        
    fAccountID,        
    fDate,        
    fPurseID,        
    fOldBalance,        
   '+@WhereInField+',        
    fFee1,        
    fFee2,        
    fFee3,        
    fFee4,        
    fNewBalance)         
    VALUES(         
    ''' + @fKey_SE + ''', ''' +         
    @AccountID + ''', ''' +         
    @sDate + ''', ' +          
    CAST(@PurseID AS VARCHAR(4)) + ', ' +          
    CAST(@OldMoney AS VARCHAR(18))  + ', ' +         
    @WhereInValue +           
    CAST(@Fee1 AS VARCHAR(18)) + ', ' +         
    CAST(@Fee2 AS VARCHAR(18)) + ', ' +         
    CAST(@Fee3 AS VARCHAR(18)) + ', ' +         
    CAST(@Fee4 AS VARCHAR(18)) + ', ' +            
    CAST(@Balance AS VARCHAR(18)) + ') '          
  IF @bPRINT = 1        
  BEGIN        
   PRINT '1 ' + @fKey_SE         
   PRINT '2 ' + @AccountID         
   PRINT '3 ' +  @sDate         
   PRINT '4 ' +  CAST(@PurseID AS VARCHAR(4))          
   PRINT '5 ' +  CAST(@OldMoney AS VARCHAR(18))         
   PRINT '6 ' +  @WhereInValue            
   PRINT '7 ' +  CAST(@Fee1 AS VARCHAR(18))         
   PRINT '8 ' +  CAST(@Fee2 AS VARCHAR(18))         
   PRINT '9 ' +  CAST(@Fee3 AS VARCHAR(18))         
   PRINT '10 ' +  CAST(@Fee4 AS VARCHAR(18))         
   PRINT '11 ' +  CAST(@Balance AS VARCHAR(18))         
          
   PRINT @TabSQL        
   SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
  END         
  EXEC sp_executesql @TabSQL 
  IF @@ERROR <> 0            
  BEGIN         
     SET @Ret = '2'         
     GOTO returnErr          
  END         
 END        
         
 end  
 --汇总数据              
         
 SET @sDate = CONVERT(VARCHAR(20),@SettleTime,112) --格式 20131212        
 SET @fKey_SP  = @sDate + DBO.FN_FillZero(5, @PosID)  + @MealID + DBO.FN_FillZero(2, @PurseID)               
 SET @fKey_SO  = @sDate + DBO.FN_FillZero(5, @OperID) + @MealID + DBO.FN_FillZero(2, @PurseID)          
 SET @fKey_SE  = @sDate + DBO.FN_FillZero(8, @AccountID) + DBO.FN_FillZero(2, @PurseID)         
 SET @fKey_PDR = @sDate + DBO.FN_FillZero(5, @PosID ) + DBO.FN_FillZero(2, @PurseID)           
 SET @fKey_CE  = @sDate + DBO.FN_FillZero(8, @AccountID) + DBO.FN_FillZero(2, @PurseID)         
 SET @sDate = CONVERT(VARCHAR(20),@SettleTime,23) --格式 2013-12-12        

    
 /*        
 汇总数据1-更新POS机汇总信息        
 0,1,2,3,8,17,28,29,30,31,32对这些流水进行POS机汇总        
 对这些数据类型进行POS机汇总        
 目前POS机汇总的数据中的费用类型fCType只有0这种类型        
 */        
 IF @bPRINT = 1        
 BEGIN        
  PRINT '-----------汇总数据1-更新POS机汇总信息------------'        
  SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime        
 END          
 IF ((@AccountID <> @ErrAccID) AND         
  (@RecType in (@WtCons,@WtOfflineWater))) OR         
  (@RecType in (@WtSave,@WtTake,@WtSub,@WtRecovery,@WtCreditForLoad,        
       @WtCreditForWrite,@WtDebitForLoad,@WtPrivilege,        
       @WtCount,@WtSubClear))  --消费类的账户无效不计入        
 BEGIN        
  DECLARE @CType INT        
  SET @CType = 0  --目前POS机汇总数据中只包含0这一种费用类型        
  UPDATE T_C_SUM_Pos         
  SET fMoney = fMoney + @Amount,         
   fCount = fCount + 1,         
   fDiscount = fDiscount + @Discount         
  WHERE fKey = @fKey_SP AND fTType = @RecType AND fCType = @CType and fPurseID = @PurseID  --同时判断Key、操作类型、费用类型、应用号        
  SET @UpdateRecCount=@@rowcount
  IF @@error <> 0  --如果出现错误则回滚        
   GOTO returnErr  
           
  IF @UpdateRecCount = 0        
   INSERT INTO [T_C_SUM_Pos]        
       ([fKey], [fPosID], [fDate], [fMealID], [fTType], [fCType], [fMoney], [fCount], [fDiscount], [fPurseID])        
   VALUES (@fKey_SP , @PosID, convert(VARCHAR(20), @SETtletime,110), @MealID, @RecType, @CType, @Amount, 1, @Discount, @PurseID)        
  IF @@error <> 0  --如果出现错误则回滚        
   GOTO returnErr        
 END        
         
         
 /*        
 汇总数据2-更新POS机流水记录收取统计表 ,注意这个不是POS汇总表         
 */        
 IF @bPRINT = 1        
 BEGIN        
  PRINT '-----------汇总数据2-更新POS机流水记录收取统计表------------'        
  SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime       END          
 IF @RecType IN (@WtCons,@WtSave,@WtTake,@WtRecovery,@WtOfflineWater) --只统计消费、存款、取款的        
 BEGIN        
  IF (@RecType = @WtSave)  --存款        
  BEGIN        
   UPDATE T_B_PosDayRecs SET fSaveCount = fSaveCount+1, fSaveSum = fSaveSum + @Amount, fLastRecTime=@SETtletime        
          WHERE fKeyID = @fKey_PDR        
  SET @UpdateRecCount=@@rowcount
  IF @@error <> 0  --如果出现错误则回滚        
     GOTO returnErr  
  if @UpdateRecCount=0      
    INSERT INTO T_B_PosDayRecs(fKeyID,fPosID,fRecDate,fSaveCount,fSaveSum, fLastRecTime)         
    VALUES(@fKey_PDR ,@PosID,@SETtletime,1,@Amount,@RecvTime)
  IF @@error <> 0  --如果出现错误则回滚        
    GOTO returnErr            
  END        
  ELSE IF (@RecType = @WtTake) --取款        
  BEGIN        
   UPDATE T_B_PosDayRecs SET fTakeCount = fTakeCount+1, fTakeSum = fTakeSum + @Amount, fLastRecTime=@SETtletime        
          WHERE fKeyID = @fKey_PDR        
  SET @UpdateRecCount=@@rowcount
  IF @@error <> 0  --如果出现错误则回滚        
     GOTO returnErr  
  if @UpdateRecCount=0        
					INSERT INTO T_B_PosDayRecs(fKeyID,fPosID,fRecDate,fTakeCount,fTakeSum, fLastRecTime)         
					VALUES(@fKey_PDR ,@PosID,@SETtletime,1,@Amount,@RecvTime) 
  IF @@error <> 0  --如果出现错误则回滚        
     GOTO returnErr       
  END          
  ELSE IF (@RecType = @WtRecovery) --纠错        
  BEGIN        
   UPDATE T_B_PosDayRecs SET fPutRightCount = fPutRightCount+1, fPutRightSum = fPutRightSum + @Amount, fLastRecTime=@SETtletime        
          WHERE fKeyID = @fKey_PDR 
  SET @UpdateRecCount=@@rowcount
  IF @@error <> 0  --如果出现错误则回滚        
     GOTO returnErr  
  if @UpdateRecCount=0        
    INSERT INTO T_B_PosDayRecs(fKeyID,fPosID,fRecDate,fPutRightCount,fPutRightSum, fLastRecTime)         
    VALUES(@fKey_PDR ,@PosID,@SETtletime,1,@Amount,@RecvTime) 
  IF @@error <> 0  --如果出现错误则回滚        
     GOTO returnErr           
  END          
  ELSE --0消费 17脱机消费        
  BEGIN        
   UPDATE T_B_PosDayRecs SET fRecCount = fRecCount+1, fConsSum = fConsSum + @Amount, fLastRecTime=@SETtletime        
          WHERE fKeyID = @fKey_PDR  
  SET @UpdateRecCount=@@rowcount
  IF @@error <> 0  --如果出现错误则回滚        
     GOTO returnErr  
  if @UpdateRecCount=0       
    INSERT INTO T_B_PosDayRecs(fKeyID,fPosID,fRecDate,fRecCount,fConsSum, fLastRecTime)        
    VALUES (@fKey_PDR ,@PosID,@SETtletime,1,@Amount,@RecvTime) 
  IF @@error <> 0  --如果出现错误则回滚        
     GOTO returnErr         
  END        
 END         
          
 IF @bPRINT = 1        
 BEGIN        
  PRINT '-----------更新POS机最后更新时间------------'        
  SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime        
 END          
 UPDATE T_B_Pos SET fLastRecTime = @RecvTime WHERE fPosID = @PosID        
 IF @@error <> 0  --如果出现错误则回滚        
     GOTO returnErr          
 IF @bPRINT = 1        
 BEGIN        
  PRINT '-----------汇总数据3-更新操作员汇总信息------------'        
  SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime        
 END          
 IF @RecType IN (@WtSave,@WtTake,@WtSub,@WtLoss,@WtUnLoss,@WtMake,@WtDel,@WtRecovery,@WtChange,        
     @WtReMake,@WtModify,@WtLossAuto,@WtModifyNOCard,@WtFrozen,@WtFrozenAuto,@WtDelNOCard,@WtReissue,@WtUnFrozen,        
     @WtCreditForLoad,@WtCreditForWrite,@WtDebitForLoad,@WtPrivilege,@WtCount,@WtInto,@WtOut,        
     @WtDelAcc,@WtPinCard,@WtSubClear)        
 BEGIN        
  DECLARE @Money NUMERIC(19,2)        
  DECLARE @Count INT -- 计数次数        
  DECLARE @TType INT -- 分别对应5种费用类型 0~4        
  SET @TType = 0        
  WHILE @TType <= 4        
  BEGIN        
   SET @Money = 0.00        
   SET @Count = 0        
   IF @TType = 0   --基本费用 @TType = 0        
   BEGIN        
    SET @Count = 1            
    IF @RecType in (@WtSave,@WtTake,@WtSub,@WtLoss,@WtUnLoss,@WtRecovery,@WtChange,@WtReMake,@WtModify,        
        @WtLossAuto,@WtModifyNOCard,@WtFrozen,@WtFrozenAuto,@WtReissue,@WtUnFrozen,        
        @WtCreditForLoad,@WtCreditForWrite,@WtDebitForLoad,@WtPrivilege,@WtCount,@WtInto,@WtOut,        
        @WtDelAcc,@WtPinCard,@WtSubClear)        
     SET @Money = @Amount        
    ELSE IF @RecType = @WtMake        
     SET @Money = @Balance        
    ELSE IF @RecType in (@WtDel,@WtDelNOCard)        
     SET @Money = @OldMoney        
   END        
   ELSE IF @TType = 1 --手续费 @TType = 1        
   BEGIN        
    IF @RecType in (@WtLoss,@WtUnLoss,@WtDel,@WtChange,@WtReMake,@WtDelNOCard)        
    BEGIN        
     SET @Count = 1        
     SET @Money = @Fee1        
    END          
   else        
    goto ContinueNext        
   END        
  ELSE IF @TType = 2 --卡费 @TType = 2        
  BEGIN        
   IF @RecType in (@WtMake,@WtReMake)        
   BEGIN        
    SET @Count = 1        
    SET @Money = @Fee2        
   END        
   ELSE        
    GOTO ContinueNext        
   /*         
   IF @RecType = 6        
    SET @Money = @Fee1        
   ELSE IF @RecType = 10        
    SET @Money = @Fee4              
   */        
  END        
  ELSE IF @TType = 3 --押金 @TType = 3        
  BEGIN        
   IF @RecType in (@WtMake,@WtDel,@WtDelNOCard)        
   BEGIN        
    SET @Count = 1        
    SET @Money = @Fee3        
   END        
   ELSE        
    GOTO ContinueNext        
        
  END        
  ELSE IF @TType = 4 --管理费 @TType = 4        
  BEGIN        
   IF @RecType in (@WtSave,@WtMake,@WtCreditForLoad)        
   BEGIN        
    SET @Count = 1        
    SET @Money = @Fee4          
   END        
   ELSE        
    GOTO ContinueNext           
  END        
        
  /*当金额和数量均为0的时候，表明该操作类型不需要进行汇总或者根本就没有该费用类型，直接跳过*/        
  IF @Money = 0.00 and @Count = 0         
   GOTO ContinueNext        
  /*写汇总表中的汇总信息*/          
  UPDATE T_C_SUM_OPER         
  SET fMoney = fMoney + @Money, fCount = fCount + @Count        
  WHERE fKey = @fKey_SO  and fTType = @RecType and         
    fCType = @TType and fAppID = @PurseID  --同时判断Key、操作类型、费用类型、应用号        
  SET @UpdateRecCount=@@rowcount
  IF @@error <> 0  --如果出现错误则回滚        
     GOTO returnErr  
  if @UpdateRecCount=0       
   INSERT INTO T_C_SUM_OPER ( fKey, fOperID, fDate, fMealID, fTType,         
          fCType, fMoney, fCount, fAppID)        
   VALUES (@fKey_SO , @OperID, @sDate, @MealID, @RecType,        
     @TType, @Money, @Count, @PurseID )        
  IF @@error <> 0  --如果出现错误则回滚        
   GOTO returnErr        
  ContinueNext:        
   SET @TType = @TType + 1        
  END        
 END
  																														
         	   
 IF @@ERROR <> 0      
   GOTO returnErr          
 ReturnCommit:        
  Commit Tran        
  Return        
 ReturnErr:         
  SET @Ret = '2'        
  IF @@trancount > 0        
   Rollback Tran         
  Return        
END
go
--PROC_EDIT_2 修改账户每日汇总存储过程UP_MakeSysAccontByday

if exists (select  * from sys.all_objects where name='UP_MakeSysAccontByday' and type='P')
   drop procedure UP_MakeSysAccontByday
GO
CREATE  PROCEDURE [dbo].[UP_MakeSysAccontByday]    
      @Date nvarchar(10)     --格式：2018-08-08    
as    
begin    
  declare @OldAcount       bigint;           --原账户人数    
  declare @OldAcountMoney  numeric(18,2);    --原账户金额     
  declare @OldAcountMoneyJC int;              --原账户金额(计次)        
  declare @ConsCount       bigint;           --营业人数    
  declare @ConsMoney       numeric(18,2);    --营业金额     
  declare @ConsMoneyJC     int;              --营业金额(计次)          
  declare @khCount         int;              --开户人数    
  declare @KhtlSum         numeric(18,2);    --开户金额    
  declare @KhDpsit         numeric(18,2);    --开户押金       
  declare @KhPndge         numeric(18,2);    --开户手续费    
  declare @KhManage        numeric(18,2);    --开户管理费    
  declare @ChCount         int;              --撤户人数    
  declare @ChtlSum         numeric(18,2);    --撤户金额     
  declare @ChMoney         numeric(18,2);    --应退押金    
  declare @ChPndge         numeric(18,2);    --撤户手续费     
  declare @GsCount         int;              --挂失人数     
  declare @GsPndge         numeric(18,2);    --挂失手续费    
  declare @JgCount         int;              --解挂人数    
  declare @JgPndge         numeric(18,2);    --解挂手续费    
  declare @SvCount         int;              --存款人数    
  declare @SvPndge         numeric(18,2);    --存款管理费    
  declare @SvtlSum         numeric(18,2);    --存款金额    
  declare @TkCount         int;              --取款人数    
  declare @TktlSum         numeric(18,2);    --取款金额    
    
  declare @SvCountJC         int;              --存款人数(计次)     
  declare @SvtlSumJC         int;              --存款金额(计次)     
  declare @TkCountJC         int;              --取款人数(计次)     
  declare @TktlSumJC         int;              --取款金额(计次)   
   
  declare @HkCount         int;              --换卡人数    
  declare @HkPndge         numeric(18,2);    --换卡手续费    
  declare @BkCount         int;              --补卡人数    
  declare @BktlSum         numeric(18,2);    --补卡卡费     
  declare @BkPndge         numeric(18,2);    --补卡手续费    
  declare @JcCount         int;              --纠错人数    
  declare @JctlSum         numeric(18,2);    --纠错金额    
  declare @JcCountJC         int;            --纠错人数(计次)     
  declare @JctlSumJC         int;            --纠错金额(计次)     
  declare @SbCount         int;              --补助人数      
  declare @SbtlSum         numeric(18,2);    --补助金额    
  declare @SbCountJC         int;            --补助人数(计次)       
  declare @SbtlSumJC         int;            --补助金额(计次)    
  declare @sbClearCount    int;              --补助清除人数    
  declare @sbClearSum      numeric(18,2);    --补助清除金额    
  declare @sbClearCountJC    int;            --补助清除人数(计次)      
  declare @sbClearSumJC      int;            --补助清除金额(计次)     
  declare @QCCount         int;              --圈存人数    
  declare @QCtlSum         numeric(18,2);    --圈存金额    
  declare @QCBXCount       int;              --圈存补款人数    
  declare @QCBXtlSum       numeric(18,2);    --圈存补款金额    
  declare @NewAcount       bigint;           --现账户人数    
  declare @NewAcountMoney  numeric(18,2);    --现账户金额     
  declare @NewAcountMoneyJC int;            --现账户金额(计次)      
  declare @Begin varchar(10)    
  declare @End   varchar(10)    
  declare @BeginAll varchar(10)    
  declare @iRet int               --人员账户每日结余表    
  declare @sRet nvarchar(2000)       
  declare @iRecRet int            --消费记录表    
  declare @sRecRet nvarchar(2000)    
  declare @iRetAll int               --人员账户每日结余表    
  --declare @sRetAll nvarchar(2000)         
  declare @SQL  nvarchar(4000)      
  declare @RecvTime datetime      
  declare @TableName_SE varchar(30)    
    
     
  set @RecvTime= cast(@Date as datetime)    
  EXEC SP_Wst_CheckSumEmpTable @RecvTime, @TableName_SE output     
   
  --在指定日期人员账户每日汇总表T_C_SumEmp_201808没有数据时查询一个月内的    
 -- set @BeginAll=CONVERT(varchar(10),DateAdd(dd,-3000,cast(@Date as datetime)),120)    
  set @Begin=CONVERT(varchar(10),DateAdd(dd,-30,cast(@Date as datetime)),120)    
  set @End=@Date    
  --人员账户每日汇总表，流水记录表  
  --EXEC UP_R_CheckTime @BeginAll, @End, 5, @iRetAll output, @sRetAll output     
  EXEC UP_R_CheckTime @Begin, @End, 5, @iRet output, @sRet output       
  EXEC UP_R_CheckTime @Begin, @End, 1, @iRecRet output, @sRecRet output          
  if @iRet = -9999 OR @sRet = ''        
  begin      
   SET @OldAcount = 0;          
   SET @OldAcountMoney=0     
   set @OldAcountMoney=0  
  end         
  else        
  BEGIN                
   --汇总期初    
   --从前一天的账户结余汇总表中取期末账户人数，如果没有数据，期初就赋值为0    
   print '**********开始处理每日账户结余表**********'    
   if not exists(select * from  T_C_SysAccontdDay where fDate=dateadd(dd,-1,@Date))    
   begin    
      set @OldAcount=0    
      set @OldAcountMoney=0   
      set @OldAcountMoney=0   
   end    
   else    
   begin    
    
  
   set @SQL='select  @OldAcount=fNewAcount,@OldAcountMoney=ISNULL(fNewAcountMoney,0) from T_C_SysAccontdDay where  convert(varchar(10),fDate,120)='''+convert(varchar(10),dateadd(dd,-1,@Date),120)+''''    
   print '从前一天账户结余汇总表中取出期末人数，期末余额:'+@sql    
   exec sp_executesql @sql,N'@OldAcount int output,@OldAcountMoney  numeric(18,2) output',@OldAcount output,@OldAcountMoney output     
   end    
     
   set @SQL='SELECT @OldAcountMoneyJC=SUM(OldAcountMoneyJC) FROM (select ISNULL(fNewAcountMoneyJC,0)OldAcountMoneyJC from T_C_SysAccontdDay where  convert(varchar(10),fDate,120)='''+convert(varchar(10),dateadd(dd,-1,@Date),120)+'''  
   UNION ALL SELECT 0 OldAcountMoneyJC )T  
   '    
   print '从前一天账户结余汇总表中取出期末计次余额:'+@sql    
   exec sp_executesql @sql,N'@OldAcountMoneyJC  numeric(18,2) output',@OldAcountMoneyJC output     
   end    
     
       
 select @ConsCount = ISNULL(SUM(fCount),0),@ConsMoney = ISNULL(SUM(fMoney),0) from T_C_SUM_Pos  where convert(varchar(10),fDate,120)=@Date and fttype in (0,17)      
  AND fPurseID not in (select fPurseCode from T_B_PurseCode where fPurseType=1 )   
   
 
    
  select           
  @khCount = ISNULL(SUM( (case when fTType = 6 and fCType = 0 then fCount else 0 end) ),0),         -- 开户人数          
  @KhtlSum = ISNULL(SUM( (case when fTType = 6 and fCType = 0 then fMoney else 0 end) ),0),         -- 开户金额           
  @KhDpsit = ISNULL(SUM( (case when fTType = 6 and fCType = 3 then fMoney else 0 end) ),0),         -- 开户押金          
  @KhPndge = ISNULL(SUM( (case when fTType = 6 and fCType = 2 then fMoney else 0 end) ),0),         -- 开户卡费          
  @KhManage = ISNULL(SUM( (case when fTType = 6 and fCType = 4 then fMoney else 0 end) ),0),        -- 管理费          
          
  @ChCount = ISNULL(SUM( (case when fTType in (7,25) and fCType = 0 then fCount else 0 end) ),0),   -- 撤户人数          
  @ChtlSum = ISNULL(SUM( (case when fTType in (7,25) and fCType = 0 then fMoney else 0 end) ),0),   -- 撤户金额          
  @ChMoney = ISNULL(SUM( (case when fTType in (7,25) and fCType = 3 then fMoney else 0 end) ),0),   -- 撤户押金          
  @ChPndge = ISNULL(SUM( (case when fTType in (7,25) and fCType = 1 then fMoney else 0 end) ),0),   -- 撤户手续费          
          
  @GsCount = ISNULL(SUM( (case when fTType = 4 and fCType = 0 then fCount else 0 end) ),0),         -- 挂失人数          
  @GsPndge = ISNULL(SUM( (case when fTType = 4 and fCType = 1 then fMoney else 0 end) ),0),         -- 挂失手续费          
          
  @JgCount = ISNULL(SUM( (case when fTType = 5 and fCType = 0 then fCount else 0 end) ),0),         -- 解挂人数          
  @JgPndge = ISNULL(SUM( (case when fTType = 5 and fCType = 1 then fMoney else 0 end) ),0),         -- 解挂手续费          
          
  @SvCount = ISNULL(SUM( (case when fTType = 1 and fCType = 0 then fCount else 0 end) ),0),         -- 存款人数          
  @SvPndge = ISNULL(SUM( (case when fTType = 1 and fCType = 1 then fMoney else 0 end) ),0),         -- 存款手续费          
  @SvtlSum = ISNULL(SUM( (case when fTType = 1 and fCType = 0 then fMoney else 0 end) ),0),         -- 存款金额          
      
  @TkCount = ISNULL(SUM( (case when fTType = 2 and fCType = 0 then fCount else 0 end) ),0),         -- 取款人数          
  @TktlSum = ISNULL(SUM( (case when fTType = 2 and fCType = 0 then fMoney else 0 end) ),0),         -- 取款金额          
          
  @HkCount = ISNULL(SUM( (case when fTType = 9 and fCType = 0 then fCount else 0 end) ),0),         -- 换卡人数          
  @HkPndge = ISNULL(SUM( (case when fTType = 9 and fCType = 1 then fMoney else 0 end) ),0),         -- 换卡手续费          
          
  @BkCount = ISNULL(SUM( (case when fTType = 10 and fCType = 0 then fCount else 0 end) ),0),        -- 补卡人数          
  @BktlSum = ISNULL(SUM( (case when fTType = 10 and fCType = 2 then fMoney else 0 end) ),0),        -- 补卡卡费          
  @BkPndge = ISNULL(SUM( (case when fTType = 10 and fCType = 1 then fMoney else 0 end) ),0),        -- 补卡手续费          
          
  @JcCount = ISNULL(SUM( (case when fTType = 8 and fCType = 0 then fCount else 0 end) ),0),         -- 纠错人数          
  @JctlSum = ISNULL(SUM( (case when fTType = 8 and fCType = 0 then fMoney else 0 end) ),0),         -- 纠错金额          
          
  @SbCount = ISNULL(SUM( (case when fTType = 3 and fCType = 0 then fCount else 0 end) ),0),         -- 补助人数          
  @SbtlSum = ISNULL(SUM( (case when fTType = 3 and fCType = 0 then fMoney else 0 end) ),0),         -- 补助金额          
            
  @SbClearCount =  ISNULL(SUM( (case when fTType = 37 and fCType = 0 then fCount else 0 end) ),0),     -- 补助清零人数          
  @SbClearSum   =  ISNULL(SUM( (case when fTType = 37 and fCType = 0 then fMoney else 0 end) ),0),     -- 补助清零金额          
            
  @QCCount = ISNULL(SUM( (case when fTType = 28 and fCType = 0 then fCount else 0 end) ),0),        -- 圈存人数          
  @QCtlSum = ISNULL(SUM( (case when fTType = 28 and fCType = 0 then fMoney else 0 end) ),0),        -- 圈存金额          
          
  @QCBXCount = ISNULL(SUM( (case when fTType = 29 and fCType = 0 then fCount else 0 end) ),0),      -- 圈存补写人数          
  @QCBXtlSum = ISNULL(SUM( (case when fTType = 29 and fCType = 0 then fMoney else 0 end) ),0)       -- 圈存补写金额            
  from T_C_SUM_OPER where convert(varchar(10),fDate,120)=@Date  and fAppID not in   
  (select fPurseCode from T_B_PurseCode where fPurseType=1 )   
    
    
   
  select           
  @SvCountJC = ISNULL(SUM( (case when fTType = 1 and fCType = 0 then fCount else 0 end) ),0),         -- 存款人数(计次)              
  @SvtlSumJC = ISNULL(SUM( (case when fTType = 1 and fCType = 0 then fMoney else 0 end) ),0),         -- 存款金额(计次)          
          
  @TkCountJC = ISNULL(SUM( (case when fTType = 2 and fCType = 0 then fCount else 0 end) ),0),         -- 取款人数(计次)          
  @TktlSumJC = ISNULL(SUM( (case when fTType = 2 and fCType = 0 then fMoney else 0 end) ),0),         -- 取款金额(计次)    
    
  @JcCountJC = ISNULL(SUM( (case when fTType = 8 and fCType = 0 then fCount else 0 end) ),0),         -- 纠错人数(计次)         
  @JctlSumJC = ISNULL(SUM( (case when fTType = 8 and fCType = 0 then fMoney else 0 end) ),0),         -- 纠错金额(计次)           
      
  @SbCountJC = ISNULL(SUM( (case when fTType = 3 and fCType = 0 then fCount else 0 end) ),0),         -- 补助人数(计次)           
  @SbtlSumJC = ISNULL(SUM( (case when fTType = 3 and fCType = 0 then fMoney else 0 end) ),0),         -- 补助金额(计次)           
            
  @SbClearCountJC =  ISNULL(SUM( (case when fTType = 37 and fCType = 0 then fCount else 0 end) ),0),     -- 补助清零人数 (计次)          
  @SbClearSumJC   =  ISNULL(SUM( (case when fTType = 37 and fCType = 0 then fMoney else 0 end) ),0)     -- 补助清零金额(计次)           
     
  from T_C_SUM_OPER where convert(varchar(10),fDate,120)=@Date  and fAppID  in   
  (select fPurseCode from T_B_PurseCode where fPurseType=1 )   
    
   select @ConsMoneyJC = ISNULL(SUM(fMoney),0)+@JctlSumJC from T_C_SUM_Pos  where convert(varchar(10),fDate,120)=@Date and fttype in (0,17)      
  AND fPurseID  in (select fPurseCode from T_B_PurseCode where fPurseType=1 )     
    
 --汇总期末    
     
  print '期末账户人数=期初账户人数+开户人数-撤户人数'    
  set @NewAcount=@OldAcount+@khCount-@ChCount     
  
  set @SQL='declare @PurseCode int   
  set @NewAcountMoney=0  
  declare  Cur_PurseCode cursor for      
      select fPurseCode from t_b_pursecode order by fPurseCode  
  open Cur_PurseCode      
  fetch next  from Cur_PurseCode into @PurseCode  
  while @@fetch_status = 0      
  begin   
   select @NewAcountMoney=@NewAcountMoney+ISNULL(sum(t.fNewBalance),0) from  
  (select *,row_number() over (partition by fAccountID order by fDate desc) rn   
  from '+@sRet+'  where    
  fPurseID not in (select fPurseCode from T_B_PurseCode where fPurseType=1 ) and  convert(varchar(10),fDate,120)<='''+@Date+'''   
    and fAccountID IN (SELECT fAccountID from t_b_Employee where fCard_State not in (3)) and fPurseID=@PurseCode) t  
  where rn=1;  
  fetch next from Cur_PurseCode into @PurseCode  
  end      
  close Cur_PurseCode      
  deallocate  Cur_PurseCode'  
    
  print '查询日期当天非记次钱包金额汇总做为期末:'+@sql    
  exec sp_executesql @sql,N'@NewAcountMoney  numeric(18,2) output',@NewAcountMoney output    
  set @NewAcountMoney=ISNULL(@NewAcountMoney,0)    
    
    
  set @SQL='declare @PurseCode int   
  set @NewAcountMoneyJC=0  
  declare  Cur_PurseCode cursor for      
      select fPurseCode from t_b_pursecode order by fPurseCode  
  open Cur_PurseCode      
  fetch next  from Cur_PurseCode into @PurseCode  
  while @@fetch_status = 0      
  begin   
   select @NewAcountMoneyJC=@NewAcountMoneyJC+ISNULL(sum(t.fNewBalance),0) from  
  (select *,row_number() over (partition by fAccountID order by fDate desc) rn   
  from '+@sRet+'  where    
  fPurseID  in (select fPurseCode from T_B_PurseCode where fPurseType=1 ) and  convert(varchar(10),fDate,120)<='''+@Date+'''   
    and fAccountID IN (SELECT fAccountID from t_b_Employee where fCard_State not in (3)) and fPurseID=@PurseCode) t  
  where rn=1;  
  fetch next from Cur_PurseCode into @PurseCode  
  end      
  close Cur_PurseCode      
  deallocate  Cur_PurseCode'  
    
  print '查询日期当天记次钱包金额汇总做为计次钱包期末:'+@sql    
  exec sp_executesql @sql,N'@NewAcountMoneyJC  numeric(18,2) output',@NewAcountMoneyJC output    
  set @NewAcountMoneyJC=ISNULL(@NewAcountMoneyJC,0)   
    
    
  print '开始汇总每日结余表'      
      
  if @Date<CONVERT(varchar(10),GETDATE(),120)    
  begin    
      
   update T_C_SysAccontdDay set fdate=@Date,fOldAcount=@OldAcount,fOldAcountMoney=@OldAcountMoney,fConsCount=@ConsCount,fConsMoney=@ConsMoney,    
     fkhCount=@khCount,fKhtlSum=@KhtlSum,fKhDpsit=@KhDpsit,fKhPndge=@KhPndge,fKhManage=@KhManage,fChCount=@ChCount,fChtlSum=@ChtlSum,fChPndge=@ChPndge,    
     fChMoney=@ChMoney,fChTkMoney=@ChtlSum + @ChMoney - @ChPndge,fSvCount=@SvCount,fSvtlSum=@SvtlSum,fSvPndge=@SvPndge,fTkCount=@TkCount,fTktlSum=@TktlSum,    
     fGsCount=@GsCount,fGsPndge=@GsPndge,fJgCount=@JgCount,fJgPndge=@JgPndge,fHkCount=@HkCount,fHkPndge=@HkPndge,fBkCount=@BkCount,fBktlSum=@BktlSum,    
     fBkPndge=@BkPndge,fJcCount=@JcCount,fJctlSum=@JctlSum,fSbCount=@SbCount,fSbtlSum=@SbtlSum,fsbClearCount=@sbClearCount,fsbClearSum=@sbClearSum,fQCCount=@QCCount,    
     fQCtlSum=@QCtlSum,fQCBXCount=@QCBXCount,fQCBXtlSum=@QCBXtlSum,fNewAcount=@NewAcount,fNewAcountMoney=@NewAcountMoney,  
     fOldAcountMoneyJC=@OldAcountMoneyJC,fNewAcountMoneyJC=@NewAcountMoneyJC,fConsMoneyJC=@ConsMoneyJC ,fSbCountJC=@SbCountJC,fSbtlSumJC=@SbtlSumJC,  
     fSbClearCountJC=@SbClearCountJC,fSbClearSumJC=@SbClearSumJC,fJcCountJC=@JcCountJC,fJctlSumJC=@JctlSumJC,  
     fSaveCountJC=@SvCountJC,fSaveMoneyJC=@SvtlSumJC,fTakeCountJC=@TkCountJC,fTakeMoneyJC=@TktlSumJC  
       
   where convert(varchar(10),fDate,120)=@Date    
    
   IF @@rowcount = 0     
   insert into T_C_SysAccontdDay select @Date,@OldAcount,@OldAcountMoney,@ConsCount,@ConsMoney,@khCount,@KhtlSum,@KhDpsit,@KhPndge,@KhManage,@ChCount,@ChtlSum,@ChPndge,    
     @ChMoney,@ChtlSum + @ChMoney - @ChPndge,@SvCount,@SvtlSum,@SvPndge,@TkCount,@TktlSum,@GsCount,@GsPndge,@JgCount,@JgPndge,@HkCount,@HkPndge,@BkCount,@BktlSum,    
     @BkPndge,@JcCount,@JctlSum,@SbCount,@SbtlSum,@sbClearCount,@sbClearSum,@QCCount,@QCtlSum,@QCBXCount,@QCBXtlSum,@NewAcount,@NewAcountMoney,  
     @OldAcountMoneyJC,@NewAcountMoneyJC,@ConsMoneyJC,@SbCountJC,@SbtlSumJC,@SbClearCountJC,@SbClearSumJC,@JcCountJC,@JctlSumJC,  
     @SvCountJC,@SvtlSumJC,@TkCountJC,@TktlSumJC     
  end    
  else    
  begin    
   update T_C_SysAccontdToDay set fdate=@Date,fOldAcount=@OldAcount,fOldAcountMoney=@OldAcountMoney,fConsCount=@ConsCount,fConsMoney=@ConsMoney,    
     fkhCount=@khCount,fKhtlSum=@KhtlSum,fKhDpsit=@KhDpsit,fKhPndge=@KhPndge,fKhManage=@KhManage,fChCount=@ChCount,fChtlSum=@ChtlSum,fChPndge=@ChPndge,    
     fChMoney=@ChMoney,fChTkMoney=@ChtlSum + @ChMoney - @ChPndge,fSvCount=@SvCount,fSvtlSum=@SvtlSum,fSvPndge=@SvPndge,fTkCount=@TkCount,fTktlSum=@TktlSum,    
     fGsCount=@GsCount,fGsPndge=@GsPndge,fJgCount=@JgCount,fJgPndge=@JgPndge,fHkCount=@HkCount,fHkPndge=@HkPndge,fBkCount=@BkCount,fBktlSum=@BktlSum,    
     fBkPndge=@BkPndge,fJcCount=@JcCount,fJctlSum=@JctlSum,fSbCount=@SbCount,fSbtlSum=@SbtlSum,fsbClearCount=@sbClearCount,fsbClearSum=@sbClearSum,fQCCount=@QCCount,    
     fQCtlSum=@QCtlSum,fQCBXCount=@QCBXCount,fQCBXtlSum=@QCBXtlSum,fNewAcount=@NewAcount,fNewAcountMoney=@NewAcountMoney,  
     fOldAcountMoneyJC=@OldAcountMoneyJC,fNewAcountMoneyJC=@NewAcountMoneyJC,fConsMoneyJC=@ConsMoneyJC  ,fSbCountJC=@SbCountJC,fSbtlSumJC=@SbtlSumJC,  
     fSbClearCountJC=@SbClearCountJC,fSbClearSumJC=@SbClearSumJC,fJcCountJC=@JcCountJC,fJctlSumJC=@JctlSumJC,  
     fSaveCountJC=@SvCountJC,fSaveMoneyJC=@SvtlSumJC,fTakeCountJC=@TkCountJC,fTakeMoneyJC=@TktlSumJC    
   where convert(varchar(10),fDate,120)=@Date    
    
   IF @@rowcount = 0     
   insert into T_C_SysAccontdToDay select @Date,@OldAcount,@OldAcountMoney,@ConsCount,@ConsMoney,@khCount,@KhtlSum,@KhDpsit,@KhPndge,@KhManage,@ChCount,@ChtlSum,@ChPndge,    
     @ChMoney,@ChtlSum + @ChMoney - @ChPndge,@SvCount,@SvtlSum,@SvPndge,@TkCount,@TktlSum,@GsCount,@GsPndge,@JgCount,@JgPndge,@HkCount,@HkPndge,@BkCount,@BktlSum,    
     @BkPndge,@JcCount,@JctlSum,@SbCount,@SbtlSum,@sbClearCount,@sbClearSum,@QCCount,@QCtlSum,@QCBXCount,@QCBXtlSum,@NewAcount,@NewAcountMoney,  
     @OldAcountMoneyJC,@NewAcountMoneyJC,@ConsMoneyJC,@SbCountJC,@SbtlSumJC,@SbClearCountJC,@SbClearSumJC,@JcCountJC,@JctlSumJC,  
     @SvCountJC,@SvtlSumJC,@TkCountJC,@TktlSumJC     
       
  end    
  print '**********每日账户结余表处理完成**********'        
     
end    
GO

--PROC_EDIT_3 修改存储过程SP_Wst_CheckSumEmpTable，增加字段
if exists(select * from dbo.sysobjects where name='SP_Wst_CheckSumEmpTable' and type='P')
   drop procedure [dbo].[SP_Wst_CheckSumEmpTable]
go
   
CREATE procedure [dbo].[SP_Wst_CheckSumEmpTable]   
    @datetime datetime,  
  @Ret varchar(30) output   
as  
 declare @TableName varchar(30)  
 declare @createsql nvarchar(4000)  
 declare @PRI nvarchar(300)  
 declare @EndSQL nvarchar(300)  
  
 select @TableName='T_C_SumEmp_' + CONVERT(varchar(6), @datetime, 112)  
 select @Ret = @TableName  
 select @PRI =  
 ' PRIMARY KEY CLUSTERED   
 (  
  [fKeyID] ASC  
 ) ON [PRIMARY] '  
 --select @EndSQL = ''  
 --非聚集索引  
 --select @PRI = ''   
 select @EndSQL =  
 'CREATE NONCLUSTERED INDEX [FK_Sett_' + @TableName +'] ON ' + @TableName + '   
 (    [fKeyID] ASC,  
   [fDate] ASC,  
   [fAccountID] ASC,  
   [fPurseID] ASC  
 ) '    
   
 if not exists (select * from dbo.sysobjects where id = object_id(N'['+@TableName+']') and OBJECTPROPERTY(id, N'IsUserTable') = 1)  
 begin  
   set @createsql=  
    ' CREATE TABLE ['+@TableName+'] (  
     [fKeyID] [varchar](20) NOT NULL,  
  [fAccountID] [varchar](8) NOT NULL,  
  [fDate] [datetime] NOT NULL,  
  [fPurseID] [int] NOT NULL,  
  [fOldBalance] [numeric](19, 2) NOT NULL,  
  [fConsCount] [int] NOT NULL DEFAULT ((0)),  
  [fConsMoney] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),
  [fLimitConsCount] [int] NOT NULL DEFAULT ((0)),  
  [fLimitConsMoney] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),    
  [fSaveCount] [int] NOT NULL DEFAULT ((0)),  
  [fSaveMoney] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),  
  [fTakeCount] [int] NOT NULL DEFAULT ((0)),  
  [fTakeMoney] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),  
  [fSubCount] [int] NOT NULL DEFAULT ((0)),  
  [fSubMoney] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),  
  [fClearCount] [int] NOT NULL DEFAULT ((0)),  
  [fClearMoney] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),  
  [fPutRightCount] [int] NOT NULL DEFAULT ((0)),  
  [fPutRightMoney] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),  
  [fDiscountCount] [int] NOT NULL DEFAULT ((0)),  
  [fDiscountMoney] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),  
  [fFee1] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),  
  [fFee2] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),  
  [fFee3] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),  
  [fFee4] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),  
  [fNewBalance] [numeric](19, 2) NOT NULL,   
        ' + @PRI  + '  
  ) ON [PRIMARY]   
  ' + @EndSQL  
  print @createsql  
  exec(@createsql)  
  if @@error <> 0   
  begin  
    Set @Ret = ''  
    Return  
  end  
 end  
 go
--PROC_EDIT_4 修改存储过程SP_Wst_CheckConsEmpTable，增加字段 
if exists(select * from dbo.sysobjects where name='SP_Wst_CheckConsEmpTable' and type='P')
   drop procedure [dbo].[SP_Wst_CheckConsEmpTable]
go
   
create procedure [dbo].[SP_Wst_CheckConsEmpTable] 
    @datetime datetime,
 	@Ret varchar(30) output 
as
	declare @TableName varchar(30)
	declare @createsql nvarchar(4000)
	declare @PRI nvarchar(300)
	declare @EndSQL nvarchar(300)

	select @TableName='T_C_ConsEmp_' + CONVERT(varchar(6), @datetime, 112)
	select @Ret = @TableName
	select @PRI =
	' PRIMARY KEY CLUSTERED 
	(
	 [fKeyID] ASC
	) ON [PRIMARY] '
	--select @EndSQL = ''
	--非聚集索引
	--select @PRI = '' 
	select @EndSQL =
	'CREATE NONCLUSTERED INDEX [FK_Sett_' + @TableName +'] ON ' + @TableName + ' 
	(    [fKeyID] ASC,
		 [fDate] ASC,
		 [fAccountID] ASC,
		 [fPurseID] ASC
	) '		
	
	if not exists (select * from dbo.sysobjects where id = object_id(N'['+@TableName+']') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	begin
	  set @createsql=
	   ' CREATE TABLE ['+@TableName+'] (
	    [fKeyID] [varchar](20) NOT NULL,
		[fAccountID] [varchar](8) NOT NULL,
		[fDate] [datetime] NOT NULL,
		[fPurseID] [int] NOT NULL,
		[fDayMoney] [numeric](19, 2) NOT NULL,
		[fDayCount] [int] NOT NULL DEFAULT ((0)),
		[fMeal1Money] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),
		[fMeal1Count] [int] NOT NULL DEFAULT ((0)),
		[fMeal2Money] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),
		[fMeal2Count] [int] NOT NULL DEFAULT ((0)),
		[fMeal3Money] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),
		[fMeal3Count] [int] NOT NULL DEFAULT ((0)),
		[fMeal4Money] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),
		[fMeal4Count] [int] NOT NULL DEFAULT ((0)),
		[fMeal5Money] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),
		[fMeal5Count] [int] NOT NULL DEFAULT ((0)),
		[fMeal6Money] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),
		[fMeal6Count] [int] NOT NULL DEFAULT ((0)),
		[fMeal7Money] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),
		[fMeal7Count] [int] NOT NULL DEFAULT ((0)),
		[fMeal8Money] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),
		[fMeal8Count] [int] NOT NULL DEFAULT ((0)),
		[fLimitMeal1Money] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),
		[fLimitMeal1Count] [int] NOT NULL DEFAULT ((0)),
		[fLimitMeal2Money] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),
		[fLimitMeal2Count] [int] NOT NULL DEFAULT ((0)),
		[fLimitMeal3Money] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),
		[fLimitMeal3Count] [int] NOT NULL DEFAULT ((0)),
		[fLimitMeal4Money] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),
		[fLimitMeal4Count] [int] NOT NULL DEFAULT ((0)),
		[fLimitMeal5Money] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),
		[fLimitMeal5Count] [int] NOT NULL DEFAULT ((0)),
		[fLimitMeal6Money] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),
		[fLimitMeal6Count] [int] NOT NULL DEFAULT ((0)),
		[fLimitMeal7Money] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),
		[fLimitMeal7Count] [int] NOT NULL DEFAULT ((0)),
		[fLimitMeal8Money] [numeric](19, 2) NOT NULL DEFAULT ((0.00)),
		[fLimitMeal8Count] [int] NOT NULL DEFAULT ((0)),		
        ' + @PRI  + '
		) ON [PRIMARY] 
		' + @EndSQL
		print @createsql
		exec(@createsql)
		if @@error <> 0 
		begin
		  Set @Ret = ''
		  Return
		end
	end
 go
 
 --PROC_EDIT_5 修改存储过程，增加fPosID
 if exists(select * from dbo.sysobjects where name='SP_Cash_CheckRecTable' and type='P')
   drop procedure [dbo].[SP_Cash_CheckRecTable]
go   
CREATE procedure [dbo].[SP_Cash_CheckRecTable]     
@Station varchar(2)     
as    
Begin    
 declare @TableName varchar(30)    
 declare @createsql nvarchar(4000)    
 declare @PRI nvarchar(300)    
 select @TableName='T_C_Cashdata' + @Station    
  select @PRI =    
  ' PRIMARY KEY CLUSTERED     
  (    
   [fConsTime] ASC,      
   [fAccountID] ASC,    
   [fSerialNo] ASC,    
   [fPurseID] ASC,    
   [fAmount] ASC    
  ) ON [PRIMARY] '    
    
 if not exists (select * from dbo.sysobjects where id = object_id(N'['+@TableName+']') and OBJECTPROPERTY(id, N'IsUserTable') = 1)    
 begin    
   set @createsql=    
    ' CREATE TABLE ['+@TableName+'] (    
  [fKeyID]       [int] IDENTITY (1, 1) NOT NULL,    
  [fAccountID]  [varchar](18) NOT NULL,     
  [fSerialNo] [varchar](30) NOT NULL,    
  [fPurseID]       [int] NOT NULL default(0),    
  [fConsTime]   [datetime] NOT NULL,      
  [fRecType]  [varchar](2) NULL,       
  [fAmount]   [numeric](9, 2) NOT NULL,    
  [fStationid]  [varchar](2) NULL, 
  [fPosID]  [int] NOT NULL default(0),        
  [fSettleTime]  [datetime] NOT NULL DEFAULT(GETDATE()),    
        ' + @PRI  + '    
  ) ON [PRIMARY]     
  '     
  --print @createsql    
  exec(@createsql)    
  if @@error <> 0     
  begin    
    Return    
  end    
 end    
end
go 
--PROC_EDIT_6 修改存储过程SP_GetEmpSumInfo
if exists(select * from dbo.sysobjects where name='SP_GetEmpSumInfo' and type='P')
   drop procedure [dbo].[SP_GetEmpSumInfo]
go    
create procedure [dbo].[SP_GetEmpSumInfo]     
    @datetime datetime,    
    @AccountID varchar(8),    
    @PurseID int    
as
begin    
		DECLARE @sDate    VARCHAR(20)   --查询日期    
		DECLARE @sDateBegin    VARCHAR(20)   --查询日期    
		DECLARE @sDateEnd    VARCHAR(20)   --查询日期    
		DECLARE @TabSQL VARCHAR(max)     
		DECLARE @Where VARCHAR(100)    
		DECLARE @StrAct VARCHAR(60)    
		DECLARE @StrPurse VARCHAR(20)    
		DECLARE @TableName_CE VARCHAR(20)    
		DECLARE @TableName_SE VARCHAR(20)    
		EXEC SP_Wst_CheckConsEmpTable @datetime, @TableName_CE output    
		EXEC SP_Wst_CheckSumEmpTable @datetime, @TableName_SE output    
		SET @sDate = CONVERT(VARCHAR(20),@datetime,23)    
		SET @sDateBegin = DATENAME(YYYY, @datetime) + '-' + DATENAME(MM, @datetime) + '-1'    
		SET @sDateEnd = DATENAME(YYYY, DATEADD(MM, 1, @datetime)) + '-' + DATENAME(MM, DATEADD(MM, 1, @datetime)) + '-1'     
		IF @AccountID=''     
			SET @StrAct = ''    
		ELSE    
			SET @StrAct = ' AND fAccountID='''+@AccountID+''''    
		IF @PurseID=0     
			SET @StrPurse = ''    
		ELSE    
			SET @StrPurse = ' AND fPurseID='+CAST(@PurseID AS VARCHAR(2))    
		SET @Where = @StrAct + @StrPurse    
		SET @TabSQL =     
			'SELECT fAccountID, fPurseID,    
			SUM(m1c) AS fMeal1Count, SUM(m1m) AS fMeal1Money,    
			SUM(m2c) AS fMeal2Count, SUM(m2m) AS fMeal2Money,    
			SUM(m3c) AS fMeal3Count, SUM(m3m) AS fMeal3Money,    
			SUM(m4c) AS fMeal4Count, SUM(m4m) AS fMeal4Money,    
			SUM(m5c) AS fMeal5Count, SUM(m5m) AS fMeal5Money,    
			SUM(m6c) AS fMeal6Count, SUM(m6m) AS fMeal6Money,    
			SUM(m7c) AS fMeal7Count, SUM(m7m) AS fMeal7Money,    
			SUM(m8c) AS fMeal8Count, SUM(m8m) AS fMeal8Money,    
			Sum(ccd) AS fConsCountD,Sum(cmd) AS fConsMoneyD,     
			Sum(scd) AS fSaveCountD,Sum(smd) AS fSaveMoneyD,     
			Sum(tcd) AS fTakeCountD,Sum(tmd) AS fTakeMoneyD,     
			Sum(bcd) AS fSubCountD,Sum(bmd) AS fSubMoneyD,     
			Sum(rcd) AS fClearCountD,Sum(rmd) AS fClearMoneyD,     
			Sum(pcd) AS fPutRightCountD,Sum(pmd) AS fPutRightMoneyD,     
			Sum(ccm) AS fConsCountM,Sum(cmm) AS fConsMoneyM,     
			Sum(scm) AS fSaveCountM,Sum(smm) AS fSaveMoneyM,     
			Sum(tcm) AS fTakeCountM,Sum(tmm) AS fTakeMoneyM,     
			Sum(bcm) AS fSubCountM,Sum(bmm) AS fSubMoneyM,     
			Sum(rcm) AS fClearCountM,Sum(rmm) AS fClearMoneyM,     
			Sum(pcm) AS fPutRightCountM,Sum(pmm) AS fPutRightMoneyM,
			SUM(lm1c) AS fLimitMeal1Count, SUM(lm1m) AS fLimitMeal1Money,    
			SUM(lm2c) AS fLimitMeal2Count, SUM(lm2m) AS fLimitMeal2Money,    
			SUM(lm3c) AS fLimitMeal3Count, SUM(lm3m) AS fLimitMeal3Money,    
			SUM(lm4c) AS fLimitMeal4Count, SUM(lm4m) AS fLimitMeal4Money,    
			SUM(lm5c) AS fLimitMeal5Count, SUM(lm5m) AS fLimitMeal5Money,    
			SUM(lm6c) AS fLimitMeal6Count, SUM(lm6m) AS fLimitMeal6Money,    
			SUM(lm7c) AS fLimitMeal7Count, SUM(lm7m) AS fLimitMeal7Money,    
			SUM(lm8c) AS fLimitMeal8Count, SUM(lm8m) AS fLimitMeal8Money        
			FROM    
				(SELECT fAccountID, fDate, fPurseID,    
						fMeal1Count AS m1c,fMeal1Money AS m1m,    
						fMeal2Count AS m2c,fMeal2Money AS m2m,    
						fMeal3Count AS m3c,fMeal3Money AS m3m,    
						fMeal4Count AS m4c,fMeal4Money AS m4m,    
						fMeal5Count AS m5c,fMeal5Money AS m5m,    
						fMeal6Count AS m6c,fMeal6Money AS m6m,    
						fMeal7Count AS m7c,fMeal7Money AS m7m,    
						fMeal8Count AS m8c,fMeal8Money AS m8m,    
						0 AS ccd,0 AS cmd,     
						0 AS scd,0 AS smd,     
						0 AS tcd,0 AS tmd,     
						0 AS bcd,0 AS bmd,     
						0 AS rcd,0 AS rmd,     
						0 AS pcd,0 AS pmd,    
						0 AS ccm,0 AS cmm,     
						0 AS scm,0 AS smm,     
						0 AS tcm,0 AS tmm,     
						0 AS bcm,0 AS bmm,     
						0 AS rcm,0 AS rmm,     
						0 AS pcm,0 AS pmm,
						fLimitMeal1Count AS lm1c,fMeal1Money AS lm1m,    
						fLimitMeal2Count AS lm2c,fMeal2Money AS lm2m,    
						fLimitMeal3Count AS lm3c,fMeal3Money AS lm3m,    
						fLimitMeal4Count AS lm4c,fMeal4Money AS lm4m,    
						fLimitMeal5Count AS lm5c,fMeal5Money AS lm5m,    
						fLimitMeal6Count AS lm6c,fMeal6Money AS lm6m,    
						fLimitMeal7Count AS lm7c,fMeal7Money AS lm7m,    
						fLimitMeal8Count AS lm8c,fMeal8Money AS lm8m          
				FROM '+@TableName_CE+' WHERE fDate='''+@sDate+''' '+@Where+'    
				UNION ALL    
				SELECT fAccountID, fDate, fPurseID,    
						0 AS m1c, 0 AS m1m,    
						0 AS m2c, 0 AS m2m,    
						0 AS m3c, 0 AS m3m,    
						0 AS m4c, 0 AS m4m,    
						0 AS m5c, 0 AS m5m,    
						0 AS m6c, 0 AS m6m,    
						0 AS m7c, 0 AS m7m,    
						0 AS m8c, 0 AS m8m,    
						fConsCount AS ccd,fConsMoney AS cmd,     
						fSaveCount AS scd,fSaveMoney AS smd,     
						fTakeCount AS tcd,fTakeMoney AS tmd,     
						fSubCount AS bcd,fSubMoney AS bmd,     
						fClearCount AS rcd,fClearMoney AS rmd,     
						fPutRightCount AS pcd,fPutRightMoney AS pmd,    
						0 AS ccm,0 AS cmm,     
						0 AS scm,0 AS smm,     
						0 AS tcm,0 AS tmm,     
						0 AS bcm,0 AS bmm,     
						0 AS rcm,0 AS rmm,     
						0 AS pcm,0 AS pmm,
						0 AS lm1c, 0 AS lm1m,    
						0 AS lm2c, 0 AS lm2m,    
						0 AS lm3c, 0 AS lm3m,    
						0 AS lm4c, 0 AS lm4m,    
						0 AS lm5c, 0 AS lm5m,    
						0 AS lm6c, 0 AS lm6m,    
						0 AS lm7c, 0 AS lm7m,    
						0 AS lm8c, 0 AS lm8m         
				FROM '+@TableName_SE+' WHERE fDate='''+@sDate+''' '+@Where+'    
				UNION ALL    
				SELECT fAccountID, '''+@sDate+''' AS fDate, fPurseID,    
						0 AS m1c, 0 AS m1m,    
						0 AS m2c, 0 AS m2m,    
						0 AS m3c, 0 AS m3m,    
						0 AS m4c, 0 AS m4m,    
						0 AS m5c, 0 AS m5m,    
						0 AS m6c, 0 AS m6m,    
						0 AS m7c, 0 AS m7m,    
						0 AS m8c, 0 AS m8m,    
						0 AS ccd,0 AS cmd,     
						0 AS scd,0 AS smd,     
						0 AS tcd,0 AS tmd,     
						0 AS bcd,0 AS bmd,     
						0 AS rcd,0 AS rmd,     
						0 AS pcd,0 AS pmd,    
						Sum(fConsCount) AS ccm,Sum(fConsMoney) AS cmm,     
						Sum(fSaveCount) AS scm,Sum(fSaveMoney) AS smm,     
						Sum(fTakeCount) AS tcm,Sum(fTakeMoney) AS tmm,     
						Sum(fSubCount) AS bcm,Sum(fSubMoney) AS bmm,     
						Sum(fClearCount) AS rcm,Sum(fClearMoney) AS rmm,     
						Sum(fPutRightCount) AS pcm,Sum(fPutRightMoney) AS pmm,
						0 AS lm1c, 0 AS lm1m,    
						0 AS lm2c, 0 AS lm2m,    
						0 AS lm3c, 0 AS lm3m,    
						0 AS lm4c, 0 AS lm4m,    
						0 AS lm5c, 0 AS lm5m,    
						0 AS lm6c, 0 AS lm6m,    
						0 AS lm7c, 0 AS lm7m,    
						0 AS lm8c, 0 AS lm8m            
				FROM '+@TableName_SE+' WHERE fDate>='''+@sDateBegin+''' AND fDate<'''+@sDateEnd+''' '+@Where+'    
				GROUP BY fAccountID, fPurseID) AA    
			GROUP BY fAccountID, fPurseID    
			ORDER BY fAccountID, fPurseID'    
		--PRINT @TabSQL    
		--EXEC sp_executesql @TabSQL 
		EXEC(@TabSQL)
end 
go


--PROC_EDIT_7 创建流水表SP_Wst_CheckRecTable
if exists(select  * from sys.all_objects where name='SP_Wst_CheckRecTable' and type='P')
 drop procedure SP_Wst_CheckRecTable
 go
 CREATE procedure [dbo].[SP_Wst_CheckRecTable]       
    @datetime datetime,      
  @type int ,      
  @Ret varchar(30) output       
as      
 declare @TableName varchar(30)      
 declare @createsql nvarchar(4000)      
 declare @PRI nvarchar(300)      
 declare @EndSQL nvarchar(300)      
 if @type = 0  --      
 begin      
  select @TableName='T_C_RecC_' + CONVERT(varchar(6), @datetime, 112)      
  select @Ret = @TableName      
  select @PRI =      
  ' PRIMARY KEY CLUSTERED       
  (      
   [fCreateTime] ASC,        
   [fAccountID] ASC,      
   [fSerialNo] ASC,      
   [fPurseID] ASC,      
   [fRecType] ASC,      
   [fAmount] ASC,      
   [fPosID] ASC,  
   [fPosTranNo] ASC,  
   [fPosOffTranNo] ASC       
  ) ON [PRIMARY] '      
  select @EndSQL = ''      
 end      
 else  if @type=1      
 begin      
  set @TableName='T_C_RecS_' + CONVERT(varchar(6), @datetime, 112)      
  Set @Ret = @TableName      
  select @PRI =      
  ' PRIMARY KEY CLUSTERED       
  (      
   [fCreateTime] ASC,        
   [fAccountID] ASC,      
   [fSerialNo] ASC,      
   [fPurseID] ASC,      
   [fRecType] ASC,      
   [fAmount] ASC,      
   [fPosID] ASC,  
   [fPosTranNo] ASC,  
   [fPosOffTranNo] ASC      
  ) ON [PRIMARY] '      
  --select @EndSQL = ''      
  --非聚集索引      
  --select @PRI = ''       
  select @EndSQL =      
  'CREATE NONCLUSTERED INDEX [FK_Sett_' + @TableName +'] ON ' + @TableName + '       
  (    [fKeyID] ASC,      
    [fSettleTime] ASC,      
    [fAccountID] ASC,      
    [fSerialNo] ASC,      
    [fPurseTranNo] ASC,      
    [fPosID] ASC,      
    [fAutoID] ASC      
  )       
        '        
 end
  else if  @type=2  
 begin  
  set @TableName='T_C_FlowVerfy_' + CONVERT(varchar(6), @datetime, 112)    
  Set @Ret = @TableName    
  select @PRI = ' '    
 end 
     
 --流水判重时增加终端交易序号，查询是否存在此条终端交易数据    
 if not exists (select * from dbo.sysobjects where id = object_id(N'['+@TableName+']') and OBJECTPROPERTY(id, N'IsUserTable') = 1)      
 begin      
   set @createsql=      
    ' CREATE TABLE ['+@TableName+'] (      
     [fAutoID] [int] IDENTITY (1, 1) NOT NULL,      
  [fKeyID] [bigint] NOT NULL,      
  [fAccountID] [varchar](18) NOT NULL,       
  [fSerialNo] [varchar](30) NOT NULL,      
  [fPurseID] [int] NOT NULL default(0),      
  [fRecType] [int] NOT NULL,      
  [fPosID] [varchar](5) NOT NULL,      
  [fCreateTime] [datetime] NOT NULL,      
  [fRecvTime] [datetime] NOT NULL DEFAULT(GETDATE()),      
  [fSettleTime] [datetime] NOT NULL DEFAULT(GETDATE()),          
  [fOldBalance] [numeric](9, 2) NOT NULL,      
  [fAmount] [numeric](9, 2) NOT NULL,      
  [fNewBalance] [numeric](9, 2) NOT NULL,      
  [fFee1] [numeric](9, 2) NULL,      
  [fFee2] [numeric](9, 2) NULL,                     
  [fFee3] [numeric](9, 2) NULL,      
  [fFee4] [numeric](9, 2) NULL,       
  [fDiscount] [numeric](9, 2) NULL default(0.00),        
  [fSourceID] [int] NOT NULL default(0),      
  [fPurseTranNo] [int] NOT NULL,        
  [fCardTranNo] [int] NOT NULL,                      
  [fPosTranNo] [int] NOT NULL DEFAULT(0),           
  [fPosOffTranNo] [int] NOT NULL DEFAULT(0),       
  [fSiteID] [varchar](2) NULL,           
  [fDeptCode] [varchar](18) NULL,      
  [fOperID] int NULL,      
  [fMealID] [varchar](3) NULL,      
  [fTaskID] int NULL,      
  [fReserve1] int NULL,      
  [fReserve2] [numeric](9, 2) NULL,      
  [fReserve3] [varchar](50) NULL,      
  [fRecKey] [varchar](200) NULL,     
  [fExternalOrder] [varchar](100) NOT NULL default'''',    
        ' + @PRI  + '      
  ) ON [PRIMARY]       
  ' + @EndSQL  
  
   if @type=2   
  set @createsql='  
  create table  ['+@TableName+']    
  (       
    [fShaValue][varchar](100) NOT NULL primary key,  
    [fFlowType][int] not null,      
    [fCreateTime] [datetime]  NOT NULL           
  )'  
      
  print @createsql      
  exec(@createsql)      
  if @@error <> 0       
  begin      
    Set @Ret = ''      
    Return      
  end      
 end       
 go

--PROC_EDIT_8 修改存储过程UP_R_CheckTime

if exists(select * from sysobjects where id = object_id(N'[UP_R_CheckTime]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
 drop procedure UP_R_CheckTime
GO
CREATE procedure [dbo].[UP_R_CheckTime] @BegDateTime datetime,  --开始查询日期    
      @EndDateTime datetime,  --结束查询日期  目前查询跨度最长为2个月    
      @RecType int = 1,       --报表类别 0:T_C_RecC_XXXXXX按交易时间  1:T_C_RecS_XXXXXX按结算时间    
      @Ret int output,    
      @RetTabel varchar(4000) output     
      as    
BEGIN    
  SET NOCOUNT ON    
  DECLARE @LOOP int,    
          @DayRet int,      
          @TName varchar(300),    
          @Time datetime,    
          @HaveTable int    
  Set @DayRet = datediff(SECOND,@BegDateTime,@EndDateTime)            
  Set @Ret = datediff(M,@BegDateTime,@EndDateTime)    
  Set @RetTabel  = ''    
  --月份不能超过100个自然月，并且开始时间必须在结束时间之前    
  if (@Ret<0) or (@Ret>100) or (@DayRet<0)    
  begin    
    set @Ret = -9999     
    Return    
  end    
  Set @LOOP = 0    
  Set @Time  = @BegDateTime    
  while (@LOOP <= @Ret)  --循环赋值    
  BEGIN    
    if @RecType = 1       --消费报表，按结算时间查询    
      SET @TName = 'T_C_RecS_' + datename(YEAR,@Time) + dbo.fn_FillZero(2,datename(MONTH,@Time))    
    else if @RecType = 0  --消费报表，按交易时间查询    
      SET @TName = 'T_C_RecC_' + datename(YEAR,@Time) + dbo.fn_FillZero(2,datename(MONTH,@Time))    
    else if @RecType = 2  --考勤报表    
      SET @TName = 'T_A_CardRecord_' + datename(YEAR,@Time) + dbo.fn_FillZero(2,datename(MONTH,@Time))    
    else if @RecType = 3  --门禁报表    
      SET @TName = 'T_E_CardRecord_' + datename(YEAR,@Time) + dbo.fn_FillZero(2,datename(MONTH,@Time))      
    else if  @RecType = 4  --个人日消费汇总表    
     SET @TName = 'T_C_ConsEmp_' + datename(YEAR,@Time) + dbo.fn_FillZero(2,datename(MONTH,@Time))   
    else if  @RecType = 5  --个人日结余汇总表    
     SET @TName = 'T_C_SumEmp_' + datename(YEAR,@Time) + dbo.fn_FillZero(2,datename(MONTH,@Time))     
       
       
    if exists (select * from dbo.sysobjects where id = object_id(N'['+@TName+']') and OBJECTPROPERTY(id, N'IsUserTable') = 1)    
      Set @HaveTable = 1    
    else    
      Set @HaveTable = 0    
    if @HaveTable = 1    
    begin      
  if @RetTabel = ''    
  begin    
          Set @RetTabel = ' select * from ' + @TName    
  end    
  else    
  begin    
    Set @RetTabel = @RetTabel + ' union all select * from ' + @TName    
  end    
    end    
    Set @Time = DATEADD(MONTH,1,@Time) --下一个月    
    Set @LOOP = @LOOP + 1    
  END    
  if @RetTabel <> ''    
    Set @RetTabel = ' (' + @RetTabel + ') AS R'    
  SET NOCOUNT OFF    
END  
go


--PROC_EDIT_9 修改存储过程SP_CreateCommonRecsView

if exists(select * from dbo.sysobjects where name='SP_CreateCommonRecsView' and xtype='P')
   drop procedure [dbo].[SP_CreateCommonRecsView]
go   
     
Create procedure [dbo].[SP_CreateCommonRecsView]  
  @Type tinyint,          --创建方式，0：所有月表；1：最近@MonCount个月；2：时间段(@BDateTime、@EDateTime)  
  @MonCount int,          --最近月份数  
  @BDateTime datetime,    --开始时间  
  @EDateTime datetime,    --结束时间  
  @ViewName varchar(50),  --创建视图的名称  
  @IsSucess int output    --是否成功 1：成功；其余失败  
as  
begin  
  declare @SqlStr nvarchar(max)=''  
  declare @BYearMonth varchar(6)  
  declare @EYearMonth varchar(6)    
  set @IsSucess = 0  
  if @Type = 0  
  begin  
    set @BYearMonth='200001'  
    set @EYearMonth=CONVERT(varchar(6), GETDATE(), 112)  
  end  
   
  if @Type = 1  
  begin  
    if @MonCount < 1 and @MonCount > 99  
    begin  
      set @IsSucess = 2  
      return  
    end    
    set @BYearMonth=CONVERT(varchar(6),DATEADD(MM,-@MonCount+1,GETDATE()), 112)  
    set @EYearMonth=CONVERT(varchar(6), GETDATE(), 112)  
  end  
   
  if @Type = 2  
  begin      
    set @BYearMonth=CONVERT(varchar(6), @BDateTime, 112)  
    set @EYearMonth=CONVERT(varchar(6), @EDateTime, 112)   
  end  
     
  if @ViewName = ''  
  begin  
    if @Type = 0  
       set @ViewName = 'V_C_RecS_ALL'  
    else if @Type = 1  
    begin  
       set @ViewName = 'V_C_RecS_Last'+RIGHT('00'+CONVERT(varchar(2), @MonCount), 2)  
    end   
    else if @Type = 2  
    begin  
       set @ViewName = 'V_C_RecS_' + @BYearMonth + @EYearMonth  
    end        
  end       
  
  declare @TableName varchar(20)  
    
  select top 1 @TableName=name from dbo.sysobjects   
   where name like '%T_C_RECS_20%' and type='U' --这里只取S表，如果要处理C表，则应为：'%T_C_RECC_20%'  
     and substring(Name,10,6)>=@BYearMonth and substring(Name,10,6)<=@EYearMonth  
     and LEN(name)=15  
    order by name desc  
    
  set @TableName='%'+@TableName+'%'  
  if exists(select S.* from sysobjects O, syscomments S   
             where O.id = S.id and S.text like @TableName and O.xtype = 'V' and O.name=@ViewName)  
  begin  
    set @IsSucess = 1  
    return  
  end  
  
  if exists(select * from dbo.sysobjects where name=@ViewName and xtype='V' )  
  begin  
    set @SqlStr = 'drop view ' + @ViewName  
    exec(@SqlStr)  
  end   
    
  declare @RecCount int  
  declare @i int    
  declare @sDataSet varchar(max)=''  
      
  select identity(int,1,1) id,name into #ls_Tb from dbo.sysobjects   
   where name like '%T_C_RECS_20%' and type='U' --这里只取S表，如果要处理C表，则应为：'%T_C_RECC_20%'  
     and substring(Name,10,6)>=@BYearMonth and substring(Name,10,6)<=@EYearMonth  
     and LEN(name)=15  
   order by name      
  select @RecCount=COUNT(*) from #ls_Tb  
  if @RecCount=0   
  begin  
    select '没有该时间段内的数据表'  
    drop table #ls_Tb  
    return  
  end  
      
  set @i=1  
  set @sDataSet=''  
  while @i<=@RecCount  
  begin  
    select @TableName=name from #ls_Tb where id=@i  
    if @i=@RecCount  
       set @sDataSet=@sDataSet + 'select * from ' + @TableName   
    else  
       set @sDataSet=@sDataSet + 'select * from ' + @TableName + CHAR(13) + ' union all ' +CHAR(13)  
    set @i=@i+1               
  end  
  drop table #ls_Tb  
    
  set @SqlStr=' Create view [dbo].['+@ViewName+'] as  
      select * from ('+@sDataSet+') r '  
  --print @SqlStr  
  exec(@SqlStr)  
  set @IsSucess = 1  
end  
go

--PROC_EDIT_10 增加创建菜品流水表UP_CheckDishRecTable

if exists(select  * from sys.all_objects where name='UP_CheckDishRecTable' and type='P')
drop procedure UP_CheckDishRecTable
GO 
create procedure [dbo].[UP_CheckDishRecTable]   
 @year int,  
  @month int   
as  
declare @TableName varchar(30)  
declare @createsql nvarchar(1000)  
set @TableName='T_D_Rec_'+cast(@year as varchar(4))+dbo.fn_FillZero(2,@month)  
if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].['+@TableName+']') and OBJECTPROPERTY(id, N'IsUserTable') = 1)  
begin  
 set @createsql=' CREATE TABLE ['+@TableName+'] ('+  
  '[fKeyID] [int] IDENTITY (1, 1) NOT NULL ,'+  
  '[fDishID] [int] NOT NULL DEFAULT (0),'+  
  '[fDishCount] [int] NOT NULL DEFAULT (0),'+  
  '[fDishPrice] [money] NOT NULL DEFAULT (0),'+  
  '[fDiscount] [int] NOT NULL DEFAULT (0),'+  
  '[fAccountID] [varchar] (18) NOT NULL ,'+  
  '[fCardNo] [varchar] (16) NOT NULL ,'+  
  '[fRecordedTime] [datetime] NOT NULL ,'+  
  '[fReceiveTime] [datetime] NOT NULL DEFAULT (getdate()),'+  
  '[fPosID] [int] NOT NULL ,'+  
  '[fRecType] [int] NOT NULL ,'+  
  '[fPosTransNo] [int] NOT NULL ,'+  
  'CONSTRAINT [PK_'+@TableName+'] PRIMARY KEY  CLUSTERED '+  
  '('+  
  '[fRecordedTime] ASC,        
   [fAccountID] ASC,      
   [fCardNo] ASC,      
   [fDishID] ASC,      
   [fDishCount] ASC,      
   [fPosID] ASC,      
   [fRecType] ASC,
   [fPosTransNo] ASC '+  
  ')  ON [PRIMARY]'+   
 ') ON [PRIMARY]'  
-- print @createsql  
 exec sp_executesql @createsql  
  
 set @createsql= 'CREATE   
   INDEX [FK_'+@TableName+'] ON [dbo].['+@TableName+'] ([fAccountID],[fDishID], [fRecType],[fPosTransNo])'  
 exec sp_executesql @createsql  
end  

go

--PROC_EDIT_11 增加菜品流水表查询UP_R_CheckTime

if exists(select  * from sys.all_objects where name='UP_R_CheckTime' and type='P')
drop procedure UP_R_CheckTime
GO 
CREATE procedure [dbo].[UP_R_CheckTime] @BegDateTime datetime,  --开始查询日期      
      @EndDateTime datetime,  --结束查询日期  目前查询跨度最长为2个月      
      @RecType int = 1,       --报表类别 0:T_C_RecC_XXXXXX按交易时间  1:T_C_RecS_XXXXXX按结算时间      
      @Ret int output,      
      @RetTabel varchar(4000) output       
      as      
BEGIN      
  SET NOCOUNT ON      
  DECLARE @LOOP int,      
          @DayRet int,        
          @TName varchar(300),      
          @Time datetime,      
          @HaveTable int      
  Set @DayRet = datediff(SECOND,@BegDateTime,@EndDateTime)              
  Set @Ret = datediff(M,@BegDateTime,@EndDateTime)      
  Set @RetTabel  = ''      
  --月份不能超过100个自然月，并且开始时间必须在结束时间之前      
  if (@Ret<0) or (@Ret>100) or (@DayRet<0)      
  begin      
    set @Ret = -9999       
    Return      
  end      
  Set @LOOP = 0      
  Set @Time  = @BegDateTime      
  while (@LOOP <= @Ret)  --循环赋值      
  BEGIN      
    if @RecType = 1       --消费报表，按结算时间查询      
      SET @TName = 'T_C_RecS_' + datename(YEAR,@Time) + dbo.fn_FillZero(2,datename(MONTH,@Time))      
    else if @RecType = 0  --消费报表，按交易时间查询      
      SET @TName = 'T_C_RecC_' + datename(YEAR,@Time) + dbo.fn_FillZero(2,datename(MONTH,@Time))      
    else if @RecType = 2  --考勤报表      
      SET @TName = 'T_A_CardRecord_' + datename(YEAR,@Time) + dbo.fn_FillZero(2,datename(MONTH,@Time))      
    else if @RecType = 3  --门禁报表      
      SET @TName = 'T_E_CardRecord_' + datename(YEAR,@Time) + dbo.fn_FillZero(2,datename(MONTH,@Time))        
    else if  @RecType = 4  --个人日消费汇总表      
     SET @TName = 'T_C_ConsEmp_' + datename(YEAR,@Time) + dbo.fn_FillZero(2,datename(MONTH,@Time))     
    else if  @RecType = 5  --个人日结余汇总表      
     SET @TName = 'T_C_SumEmp_' + datename(YEAR,@Time) + dbo.fn_FillZero(2,datename(MONTH,@Time))       
    else if @RecType = 6  --菜品报表  
      SET @TName = 'T_D_Rec_' + datename(YEAR,@Time) + dbo.fn_FillZero(2,datename(MONTH,@Time))         
         
    if exists (select * from dbo.sysobjects where id = object_id(N'['+@TName+']') and OBJECTPROPERTY(id, N'IsUserTable') = 1)      
      Set @HaveTable = 1      
    else      
      Set @HaveTable = 0      
    if @HaveTable = 1      
    begin        
  if @RetTabel = ''      
  begin      
          Set @RetTabel = ' select * from ' + @TName      
  end      
  else      
  begin      
    Set @RetTabel = @RetTabel + ' union all select * from ' + @TName      
  end      
    end      
    Set @Time = DATEADD(MONTH,1,@Time) --下一个月      
    Set @LOOP = @LOOP + 1      
  END      
  if @RetTabel <> ''      
    Set @RetTabel = ' (' + @RetTabel + ') AS R'      
  SET NOCOUNT OFF      
END    
GO

--PROC_EDIT_12 增加插入菜品流水UP_InsertDishRec

if exists(select  * from sys.all_objects where name='UP_InsertDishRec' and type='P')
drop procedure UP_InsertDishRec
GO 
create procedure [dbo].[UP_InsertDishRec]
  @CardNo VARCHAR(16),  
  @RecordedTime datetime,  
  @PosID int,  
  @DishID int,  
  @DishCount int,  
  @DishPrice money,  
  @Discount int,  
  @RecType int,   
  @PosTransNo int,  
  @Ret varchar(50) output   
AS  
declare @AccountID varchar(18)  
declare @b_Year varchar(4)  
declare @b_Month varchar(2)  
declare @ErrAccID varchar(20) --无效账号 默认由原来的01999999修改为00000000  
declare @fRecType   int 

 --1-脱机 2- 联机
	if @RecType=1 
	set @fRecType=17
	else
	set @fRecType=0

Set @ErrAccID = '00000000'  
set @Ret='1'
select  top 1 @AccountID=a.fAccountID from T_B_Cards a left join T_B_Employee b on a.fAccountID=b.fAccountID where a.fSerialNo=@CardNo


 
if @AccountID is null   
begin   
  SELECT @AccountID = fAccountID FROM T_B_CardHis WHERE fSerialNo = @CardNo and @RecordedTime >= fBeginTime and @RecordedTime < fEndTime  
end  
  
if @AccountID is null set @AccountID=@ErrAccID  
  
set @b_Year=datename(yyyy,@RecordedTime)  
set @b_Month=datename(mm,@RecordedTime)  
  
exec UP_CheckDishRecTable @b_Year,@b_Month  
  
declare @sql_table nvarchar(4000)  
  
set @sql_table=--'if not exists (select * from T_D_Rec_'+@b_Year+@b_Month+' where fAccountID='''+@AccountID+''' and fDishID='+cast(@DishID as varchar(10))+
															--' and fRecType='+cast(@fRecType as varchar(10))+' and fPosTransNo='+cast(@PosTransNo as varchar(10))+') '+  
															' INSERT INTO T_D_Rec_'+@b_Year+@b_Month+  
															' Values('+cast(@DishID as varchar(10))+',  
															'+cast(@DishCount as varchar(5))+',  
															'+cast(@DishPrice as varchar(10))+',  
															'+cast(@Discount as varchar(3))+',  
															'''+@AccountID+''',  
															'''+@CardNo+''',  
															'''+convert(varchar(19),@RecordedTime,20)+''',  
															GetDate(),'+  
															cast(@PosID as varchar(5))+',  
															'''+cast(@fRecType as varchar(10))+  
															''','''+cast(@PosTransNo as varchar(10))+''')'  
  
print @sql_table  
exec sp_executesql @sql_Table   
 
go

--PROC_EDIT_13 增加SP_SetCardHis

if exists(select  * from sys.all_objects where name='SP_SetCardHis' and type='P')
drop procedure SP_SetCardHis
GO 
create procedure [dbo].[SP_SetCardHis]   
  @fAccountID varchar(30),  --账号  
  @SerialNo varchar(30),   --应用序列号/IC卡号/ID卡号  
  @fDeptID varchar(50),   --部门编号  
  @fTime datetime,    --操作时间  
  @State int      --操作类型（流水类型）   
as  
BEGIN  
  Declare @fKeyID int  
 /*  
 0:消费 1:存款 2:取款 3:补助 4:挂失 5:解挂 6:配卡/开卡/开户   
 7:有卡撤户 8:纠错 9:换卡换卡 10:补卡补卡 11:有卡变更 12:登陆   
 13:退出 14:未正常退出 15:黑名单刷新 16:改密码 17:脱机消费 18:删除流水   
 19:删除营业 20:删除出纳 21:自动挂失 22:无卡变更 23:人工冻结 24:自动冻结   
 25:无卡撤户 26:补发卡 27:解冻 28):圈存  
 29):圈存补款/圈存补写卡 30):圈提 31:优惠 32:计次  
 33:转入 34:转出 35:删除资料 36:销卡  
 */  
   
 -- 赵茂森 2016-06-30 增加 副卡记录  
   
 --更改老记录  
 if @State in (4,5,7,9,10,21,23,24,25,26,27,36,39)  
 begin  
  if EXISTS(select * from T_B_CardHis where fAccountID = @fAccountID and fUsed = 1)  
  begin  
    select @fKeyID=fKeyID from T_B_CardHis   where fAccountID = @fAccountID and fUsed = 1  
    --如果是撤户，需要把所有在用卡改为不在用
    if @State in (7,25)  
       update T_B_CardHis set fEndTime = @fTime , fUsed = 0  where fAccountID = @fAccountID and fUsed = 1  
    else
    begin
							if @State in (5,9,10,26,27)  
										update T_B_CardHis set fEndTime = @fTime , fUsed = 0  where fKeyID = @fKeyID  
							else  
										update T_B_CardHis set fEndTime = @fTime   where fKeyID = @fKeyID 
    end   
   
  end  
 end  
  
 --建立新记录21,23,24  
 if @State in (5,6,9,10,26,27,38)  
 begin  
  --如果原来有有效的相同记录   
  if EXISTS(select * from T_B_CardHis where fAccountID = @fAccountID and fSerialNo = @SerialNo and fUsed = 1)  
  begin  
    select @fKeyID=fKeyID from T_B_CardHis   
      where fAccountID = @fAccountID and fSerialNo = @SerialNo and fUsed = 1  
    update T_B_CardHis set  fUsed = 0, fEndTime = @fTime  
   where fKeyID = @fKeyID  
  end  
    
  insert into T_B_CardHis ([fAccountID] , [fSerialNo] , [fDept] , [fBeginTime] , [fUsed])  
     VALUES(@fAccountID,    @SerialNo,  @fDeptID,   @fTime,         1)  
 end  
END  
GO


--PROC_EDIT_14 增加存储过程UP_InsertOnLineRecord_Step1 

if exists(select  * from sys.all_objects where name='UP_InsertOnLineRecord_Step1' and type='P')
drop procedure UP_InsertOnLineRecord_Step1
GO 
CREATE PROCEDURE [dbo].[UP_InsertOnLineRecord_Step1]          
  @PurseID INT,      --钱包编号        
  @FlowType INT,      --流水类型        
  @RecType INT,      --交易类型        
  @UserCardID VARCHAR(16),   --用户卡号(物理卡号/应用序列号)        
  @PosID INT,       --交易终端号        
  @CreateTime DATETIME,    --交易时间        
  @RecvTime DATETIME,     --入库时间        
  @Amount Numeric(18,2),    --交易额        
  @Discount Numeric(18,2),   --折扣额        
  @SourceID INT,      --来源        
  @TaskID INT,      --任务编号        
  @OperID INT,      --操作员编号         
  @Fee1 Numeric(18,2),    --其他费用1(手续费)        
  @Fee2 Numeric(18,2),    --其他费用2(卡费)        
  @Fee3 Numeric(18,2),    --其他费用3(押金)        
  @Fee4 Numeric(18,2),    --其他费用4(管理费)        
  @OffTranNo INT,      --卡脱机交易序号        
  @PosTranNo INT,      --终端联机交易序号         
  @PosOffTranNo INT,     --终端脱机交易序号        
  @fRecKey VARCHAR(200),    --数据校验Key值    
  @fExternalOrder VARCHAR(100),       
  @Ret int output         
AS        
BEGIN        
 /*常量定义(过程内值不可修改)*/        
 DECLARE        
  @WtCons INT = 0,   --联机消费         
  @WtSave INT = 1,   --存款        
  @WtTake INT = 2,   --取款        
  @WtSub  INT = 3,   --补助        
  @WtLoss INT = 4,   --挂失        
  @WtUnLoss INT = 5,   --解挂        
  @WtMake INT = 6,   --配卡/开卡/开户        
  @WtDel INT = 7,    --有卡撤户        
  @WtRecovery INT = 8,  --纠错        
  @WtChange INT = 9,   --换卡换卡        
  @WtReMake INT = 10,   --补卡补卡        
  @WtModify INT = 11,   --有卡变更        
  @WtLogin INT = 12,   --登陆        
  @WtLoginOut INT = 13,  --退出        
  @WtLoginOutErr INT = 14, --未正常退出        
  @WtRefreshBList INT = 15, --黑名单刷新        
  @WtResetPW INT = 16,  --改密码        
  @WtOfflineWater INT = 17, --脱机消费        
  @WtDelWater INT = 18,  --删除流水        
  @WtDelCons INT = 19,  --删除营业        
  @WtDelCashier INT = 20,  --删除出纳        
  @WtLossAuto INT = 21,  --自动挂失        
  @WtModifyNOCard INT = 22, --无卡变更        
  @WtFrozen INT = 23,   --人工冻结        
  @WtFrozenAuto  INT = 24, --自动冻结        
  @WtDelNOCard INT = 25,  --无卡撤户        
  @WtReissue INT = 26,  --补发卡        
  @WtUnFrozen INT = 27,  --解冻        
  @WtCreditForLoad INT = 28,  --圈存        
  @WtCreditForWrite INT = 29, --圈存补款/圈存补写卡        
  @WtDebitForLoad INT = 30,   --圈提        
  @WtPrivilege INT = 31,      --优惠        
  @WtCount INT = 32,          --计次        
  @WtInto INT = 33,           --转入        
  @WtOut INT = 34,            --转出        
  @WtDelAcc INT = 35,         --删除资料        
  @WtPinCard INT = 36,        --销卡        
  @WtSubClear INT = 37,       --补助清零          
  @WtAddCard  INT = 38,  --增加副卡        
  @WtDelCard  INT = 39,  --注销副卡        
  @WtEnabledPurse INT = 40, --启用钱包        
  @WtDisabledPurse INT = 41,  --停用钱包        
  @WtAllow INT = 90           --门禁授权        
 /*过程变量定义*/        
 DECLARE        
  @AccountID VARCHAR(18),        
  @StationID VARCHAR(2),   --工作站编号        
  @DeptCode VARCHAR(20),   --部门编号        
  @MealID VARCHAR(3),    --交易时段编号         
  @OldMoney Numeric(18,2),  --交易前余额        
  @Balance Numeric(18,2),   --交易后余额        
  @OLTransNo INT,     --联机交易次数        
  @SettleTime DATETIME,   --入账时间        
  @Fraptime DATETIME,    --结算时间        
  @CardState INT,     --卡片状态  
  @Card_State INT,     --账户状态       
  @iSucc INT,      --写预存流水状态         
  @ErrAccID VARCHAR(20),   --无效账号 默认由原来的01999999修改为00000000        
  @ErrCardID VARCHAR(20),   --无效逻辑卡号        
  @Record_ID VARCHAR(10),        
  @fPurseID varchar(20),
  @LimitCountEnabled bit,   --POS机是否限次    
  @LimitMoneyEnabled bit,   --POS机是否限额   
  @KhDate datetime,
  @fHaveKhWater int, --是否有开户流水 
  @IsRepeatWater int, --是否重复流水
  @IsPendingConsRec int --是否待处理流水
 /*临时变量定义*/        
 DECLARE         
  @PTime VARCHAR(100),        
  @bPrint BIT,
  @ExecResult int   /*执行结果临时保存，原因是 @@Error 结果只能被读取一次，第二次读取时状态为0 */
 --交易时间去掉毫秒部分 
 SET @CreateTime=DATEADD(ms, -DATEPART(ms, @CreateTime), @CreateTime)
     
 SET @Ret = 0  --赋值返回值初始值         
 SET @bPRINT = 1  --是否显示调试信息（用于显示各个阶段耗时）         
 SET @ErrAccID = '00000000'        
 SET @ErrCardID = '00000000'           
 SET @CardState=0 
 set @Card_State=0    
 SET @SettleTime = GETDATE()  --联机流水以当前时间下账   
 SET @fHaveKhWater=0
 set @IsRepeatWater=0
 set @IsPendingConsRec=0
 set @fPurseID=''      
 
 --根据卡号获取账户信息        
 /*        
 1.在卡表中查询 T_B_Cards        
 2.在账户卡历史表中查询 T_B_CardHis        
 */  
       
 --1.在卡表中查询卡号对应帐号        
 SELECT top 1 @AccountID=C.fAccountID,@CardState=fCardState,@Card_State=fCard_State,@DeptCode=E.fDept,@KhDate=E.fKh_Date,@fHaveKhWater=E.fHaveKhWater FROM T_B_Cards C LEFT JOIN T_B_Employee E ON E.fAccountID=C.fAccountID WHERE C.fSerialNo=@UserCardID         
 IF (@@rowcount=0)  --未查询到对应账户        
 BEGIN        
  IF @bPRINT = 1 --日志显示 0 不显示 1显示        
  BEGIN        
   PRINT '-----------从卡历史日志表查询账户信息T_B_CardHis--------------'        
   SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
  END        
  --2.在账户卡历史表中查询 T_B_CardHis       用物理卡号、流水时间去查找对应的账号     
  SELECT @AccountID = fAccountID,@DeptCode = fDept FROM T_B_CardHis WHERE fSerialNo = @UserCardID and @CreateTime >= fBeginTime and @CreateTime < fEndTime        
  IF @@rowcount=0         
  BEGIN        
   SET @AccountID=@ErrAccID    
  END  
  else
  begin
    select @fHaveKhWater=fHaveKhWater,@Card_State=fCard_State from T_B_Employee where fAccountID=@AccountID
    select @CardState=fCard_State from T_B_Employee where fAccountID=@AccountID     --解决换卡后，卡号对应不上，造成流水不上传；    
  end  
 END        
 

 IF @AccountID <> @ErrAccID        
 BEGIN        
  IF @bPRINT = 1 --日志显示 0 不显示 1显示        
  BEGIN        
   PRINT '-----------写卡历史记录表--------------'        
   SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
  END           
  IF @bPRINT = 1 --日志显示 0 不显示 1显示        
  BEGIN        
   PRINT 'EXEC SP_SETCardHis '+@AccountID+','+@UserCardID+','+@DeptCode+','+convert(varchar(10),@CreateTime,120)+','+cast(@RecType as varchar(3))        
   SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
  END         
  EXEC SP_SETCardHis @AccountID, @UserCardID,@DeptCode,@CreateTime,@RecType        
 END    
 

 IF @RecType IN (@WtMake)
   update T_B_Employee set fLastOperateTime=GETDATE(),fHaveKhWater=1 where fAccountID=@AccountID  
 ELSE
   update T_B_Employee set fLastOperateTime=GETDATE() where fAccountID=@AccountID 
   
 /*根据交易时间获取交易时段*/        
 SET @MealID = '001'
 SELECT @MealID=ISNULL(fMeal_Id, '001') FROM T_B_MealSet WHERE (CAST(fBegin_Time as time)<=CAST(@CreateTime as time)) AND (CAST(fEnd_Time as time)>=CAST(@CreateTime as time))        
       
 /*根据终端号来获取工作站号*/ 
 SET @StationID = '01' 
 SELECT @StationID=SUBSTRING(fSiteID,1,2), @LimitCountEnabled=fLimitCountEnabled,@LimitMoneyEnabled=fLimitMoneyEnabled FROM T_B_Pos WHERE fPosID=@PosID        

 --在钱包应用表中查找钱包信息  
 set @fPurseID=@AccountID+RIGHT('00'+CAST(@PurseID as varchar(2)),2)      
 SELECT @OldMoney=ISNULL(fBalance,0), @OLTransNo=ISNULL(fTransNo+1,1) FROM T_B_Purses WHERE fPurseID=@fPurseID        

 IF @@ROWCOUNT=0         
 BEGIN        
  SET @OldMoney=0        
  SET @OLTransNo=1        
  PRINT '----*****----'        
  PRINT @OldMoney        
  PRINT @OLTransNo        
  PRINT '----*****----'        
 END  
   --脱机流水的联机交易序号为0
 IF @RecType  IN (@WtOfflineWater) 
 BEGIN
   SET @PosTranNo=0
 END        
 /*根据交易额，交易前余额，手续费来计算交易后余额*/         
 IF @RecType in (@WtCons, @WtTake, @WtLoss, @WtUnLoss, @WtChange, @WtReMake, @WtModify,@WtOfflineWater, 
                 @WtReissue, @WtDebitForLoad, @WtPrivilege, @WtCount,@WtOut, @WtSubClear)         
 BEGIN        
  --余额减值交易        
  SET @Balance=@OldMoney-@Amount-@Fee1-@Fee2-@Fee4        
 END        
 ELSE IF @RecType in (@WtSave, @WtSub, @WtMake, @WtRecovery, @WtCreditForLoad, @WtCreditForWrite, @WtInto, @WtAddCard, @WtEnabledPurse)         
 BEGIN             
  --余额增值交易        
  SET @Balance=@OldMoney+@Amount-@Fee1-@Fee2-@Fee3-@Fee4        
 END        
 ELSE IF @RecType in (@WtDel, @WtDelNoCard )        
 BEGIN        
  SET @Balance=@OldMoney-@Amount-@Fee1-@Fee2       
 END        
 ELSE IF @RecType in (@WtPinCard,@WtDelCard, @WtDisabledPurse )        
 BEGIN        
  SET @Balance=@OldMoney-@Amount-@Fee1        
 END       
 ELSE BEGIN        
  SET @Balance=@OldMoney+@Amount        
 END        
        
 
 DECLARE @TabSQL_Over nVARCHAR(4000) 
 --如果流水时间小于开户时间或卡片为撤户状态的卡，就保存在过期流水表里
 if ( @AccountID = @ErrAccID ) OR  ((@CreateTime<@KhDate)or ((@Card_State=4) and (@RecType not IN (@WtDel, @WtDelNoCard ) )))  
 begin
   SET @TabSQL_Over=        
				   'INSERT INTO [T_C_Rec_OverdueRec]         
					(fAccountID,        
					fSerialNo,        
					fPurseID,        
					fRecType,        
					fPosID,        
					fCreateTime,        
					fRecvTime,        
					fAmount,        
					fDiscount,        
					fSourceID,        
					fCardTranNo,            
					fPosTranNo,        
					fMealID,        
					fRecKey,  
					fExternalOrder)         
					VALUES(         
					''' + @AccountID + ''',         
					''' + @UserCardID + ''',         
					' +  CAST(@PurseID AS VARCHAR(4)) + ',         
					''' + CAST(@RecType AS VARCHAR(2)) + ''',         
					''' + CAST(@PosID AS VARCHAR(5)) + ''',         
					''' + CONVERT(VARCHAR(40), @CreateTime, 21) + ''',         
					''' + CONVERT(VARCHAR(40), @RecvTime, 21) + ''',         
					' +CAST(@Amount AS VARCHAR(18)) + ',         
					'+ CAST(@Discount AS VARCHAR(18)) + ',         
					''' + CAST(@SourceID AS VARCHAR(3)) + ''',         
					''' + CAST(@OffTranNo AS VARCHAR(10)) + ''',             
					''' + CAST(@PosOffTranNo AS VARCHAR(10)) + ''',         
					''' + @MealID  + ''',         
					''' + @fRecKey + ''',  
					'''+ @fExternalOrder+''' ) '         
	EXEC sp_executesql @TabSQL_Over        
	IF @@ERROR <> 0                   
		SET @Ret = '2'          
	ELSE       
		SET @Ret = '0'         
	return     
 end
 
 --如果传上来的流水对应的账号是未开卡状态，就先保存在一张临时待处理表，当开卡流水上来后再处理
 if (@AccountID <> @ErrAccID ) and ( @RecType in (@WtCons,@WtSave,@WtTake,@WtSub,@WtLoss,@WtUnLoss,@WtDel,@WtRecovery,@WtChange,@WtReMake,
     @WtOfflineWater,@WtDelNOCard,@WtCreditForLoad,@WtCreditForWrite,@WtDebitForLoad,@WtPrivilege,@WtCount,@WtInto,@WtOut,@WtPinCard,@WtSubClear))
     and (@fHaveKhWater=0)    
 begin
  --待处理流水，放在第2步处理
	 set @IsPendingConsRec=1
	 insert into T_C_middle_Step1 ([fPurseID],[fRecType],[fAccountID],[fUserCardID],[fPosID],[fStationID],[fMealID],[fCreateTime],
									[fRecvTime],[fOldMoney],[fAmount],[fBalance],[fDiscount],[fOperID],[fFee1],[fFee2],[fFee3],[fFee4],[fLimitCountEnabled],
									[fFlowType],[fSourceID],[fTaskID],[fOffTranNo],[fPosTranNo],[fPosOffTranNo],
									[ffRecKey],[ffExternalOrder],[fIsRepeatWater],[fIsPendingConsRec])	
	                     values(@PurseID,@RecType,@AccountID,@UserCardID,@PosID,@StationID,@MealID,@CreateTime,
								@RecvTime,@OldMoney,@Amount,@Balance,@Discount,@OperID,@Fee1,@Fee2,@Fee3,@Fee4,@LimitCountEnabled,
							    @FlowType,@SourceID,@TaskID,@OffTranNo,@PosTranNo,@PosOffTranNo,
                                @fRecKey,@fExternalOrder,@IsRepeatWater,@IsPendingConsRec)
	  --如果写入第2步出错，就返回错误，让一卡通重新写流水
	  IF @@ERROR <> 0                  
		SET @Ret = '2'         
	  else        
		SET @Ret = '0'         
	  return 					                           
 end
        
 IF @bPrint = 1        
 BEGIN        
  PRINT '-----------创建流水表--------------'        
  SELECT @Ptime = CONVERT(varchar(100), GETDATE(), 13)  print @Ptime        
 END        
 DECLARE @TableName_C varchar(30)         
 DECLARE @TableName_S varchar(30)
 DECLARE @TableName_W varchar(30)        
 /*检查或创建流水表*/        
 EXEC SP_Wst_CheckRecTable @CreateTime,0,  @TableName_C output        
 EXEC SP_Wst_CheckRecTable @SettleTime,1, @TableName_S output   
 EXEC SP_Wst_CheckRecTable @CreateTime,2,  @TableName_W output     
        
 /*记录还原点*/        
 BEGIN TRAN        
 IF @bPrint = 1        
 BEGIN        
  PRINT '-----------获取最大编号------------'        
  SELECT @Ptime = CONVERT(varchar(100), GETDATE(), 13)  print @Ptime         
 END          
 DECLARE @MaxID bigint        
 EXEC SP_Wst_GetRecMax @MaxID output        
 IF @MaxID <= 0 --如果取得的流水最大序号小于或等于0，表明最大序号获取有问题，直接返回执行存储过程错误        
 BEGIN        
  SET @Ret = '2'        
  GOTO returnErr        
 END        
         
 DECLARE @TabSQL nVARCHAR(4000)         
 IF @FlowType=1        
 BEGIN          
  IF @bPRINT = 1        
  BEGIN        
   PRINT '-----------插入未确认流水------------'        
   SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
  END          
  SET @TabSQL= 'INSERT INTO [T_C_Rec_Unconfirmed]         
				(fAccountID,        
				fSerialNo,        
				fPurseID,        
				fRecType,        
				fPosID,        
				fCreateTime,        
				fRecvTime,        
				fAmount,        
				fDiscount,        
				fSourceID,        
				fCardTranNo,            
				fPosTranNo,        
				fMealID,        
				fRecKey,  
				fExternalOrder)         
				VALUES(         
				''' + @AccountID + ''',         
				''' + @UserCardID + ''',         
				' +  CAST(@PurseID AS VARCHAR(4)) + ',         
		  	 ''' + CAST(@RecType AS VARCHAR(2)) + ''',         
				''' + CAST(@PosID AS VARCHAR(5)) + ''',         
				''' + CONVERT(VARCHAR(40), @CreateTime, 21) + ''',         
				''' + CONVERT(VARCHAR(40), @RecvTime, 21) + ''',         
				' +CAST(@Amount AS VARCHAR(18)) + ',         
				'+ CAST(@Discount AS VARCHAR(18)) + ',         
				''' + CAST(@SourceID AS VARCHAR(3)) + ''',         
				''' + CAST(@OffTranNo AS VARCHAR(10)) + ''',             
				''' + CAST(@PosOffTranNo AS VARCHAR(10)) + ''',         
				''' + @MealID  + ''',         
				''' + @fRecKey + ''',  
				'''+ @fExternalOrder+''' ) '         
  EXEC sp_executesql @TabSQL        
  IF @@ERROR <> 0            
  BEGIN         
	SET @Ret = '2'        
	GOTO returnErr        
  END        
  ELSE BEGIN        
	SET @Ret = '0'         
	GOTO returnCommit        
  END          
 END        
 ELSE BEGIN         
  /*        
    流水按月分表存储，判断重复由表的联合主键判断        
    */                     
  --脱机流水需要判断是否重复
  IF @RecType IN (@WtOfflineWater) 
  begin
    DECLARE @FlowShaString varchar(200)
	set @FlowShaString = @AccountID+'_'+@UserCardID+'_'+CAST(@PurseID AS VARCHAR(4))+'_'+CAST(@RecType AS VARCHAR(2))+'_'+
					     CAST(@PosID AS VARCHAR(5))+'_'+CAST(@PosOffTranNo AS VARCHAR(10))+'_'+CAST(@Amount AS VARCHAR(18))
	set @FlowShaString=substring(sys.fn_varbintohexstr(hashbytes('SHA', @FlowShaString)),3,40)
    declare @iFlowCount int 
    SET @TabSQL='SELECT  @iFlowCount=count(*) FROM '+@TableName_W+' WHERE fShaValue='''+@FlowShaString+''''
    EXEC sp_executesql @TabSQL, N'@iFlowCount int output', @iFlowCount output
    IF @iFlowCount=0 
    BEGIN
      SET @TabSQL='INSERT INTO '+@TableName_W+'(fFlowType,fShaValue,fCreateTime) values('+CAST(@WtOfflineWater as varchar(2))+','''+@FlowShaString+''',GETDATE())'  
      PRINT @TabSQL
      EXEC sp_executesql @TabSQL
      IF @@ERROR <> 0            
	  BEGIN         
		SET @Ret = '2'        
		GOTO returnErr        
	  END  
    END
    else
    begin
      --重复流水，传到第2步去写，此处用goto是为了提交事务，待处理流水表是在事务之前处理的，不用goto           
		set @IsRepeatWater=1
		insert into T_C_middle_Step1 ([fPurseID],[fRecType],[fAccountID],[fUserCardID],[fPosID],[fStationID],[fMealID],[fCreateTime],
									 [fRecvTime],[fOldMoney],[fAmount],[fBalance],[fDiscount],[fOperID],[fFee1],[fFee2],[fFee3],[fFee4],[fLimitCountEnabled],
									 [fFlowType],[fSourceID],[fTaskID],[fOffTranNo],[fPosTranNo],[fPosOffTranNo],
									 [ffRecKey],[ffExternalOrder],[fIsRepeatWater],[fIsPendingConsRec])	
							   values(@PurseID,@RecType,@AccountID,@UserCardID,@PosID,@StationID,@MealID,@CreateTime,
									  @RecvTime,@OldMoney,@Amount,@Balance,@Discount,@OperID,@Fee1,@Fee2,@Fee3,@Fee4,@LimitCountEnabled,
							          @FlowType,@SourceID,@TaskID,@OffTranNo,@PosTranNo,@PosOffTranNo,
									  @fRecKey,@fExternalOrder,@IsRepeatWater,@IsPendingConsRec)
		 --如果写入第2步出错，就返回错误，让一卡通重新写流水
		 IF @@ERROR <> 0
		 BEGIN                          
		   	SET @Ret = '3'
		   	GOTO returnCommit
		 END
		 else
		 begin
		   SET @Ret = '0'
		   GOTO returnCommit 
		 end   
     end
  end 
  
  IF @bPRINT = 1        
  BEGIN        
   PRINT '-----------判断重复插入流水_C------------'        
   SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
  END   

  SET @TabSQL=        
			   'INSERT INTO ['+@TableName_C+']         
				(fKeyID,        
				fAccountID,        
				fSerialNo,        
				fPurseID,        
				fRecType,        
				fCreateTime,        
				fRecvTime,        
				fSettleTime,        
				fOldBalance,        
				fAmount,        
				fNewBalance,        
				fFee1,        
				fFee2,        
				fFee3,        
				fFee4,        
				fDiscount,        
				fSourceID,        
				fPurseTranNo,        
				fCardTranNo,        
				fPosID,        
				fPosTranNo,        
				fPosOffTranNo,        
				fSiteID,        
				fDeptCode,        
				fOperID,        
				fMealID,        
				fTaskID,        
				fRecKey,  
				fExternalOrder)         
				VALUES(         
				''' + CAST(@MaxID AS VARCHAR(30)) + ''',         
				''' + @AccountID + ''',         
				''' + @UserCardID + ''',         
				' +  CAST(@PurseID AS VARCHAR(4)) + ',         
				''' +CAST(@RecType AS VARCHAR(2)) + ''',         
				''' + CONVERT(VARCHAR(40), @CreateTime, 21) + ''',         
				''' + CONVERT(VARCHAR(40), @RecvTime, 21) + ''',         
				''' + CONVERT(VARCHAR(40), @SETtletime, 21) + ''',         
				' + CAST(@OldMoney AS VARCHAR(18))  + ',         
				' + CAST(@Amount AS VARCHAR(18)) + ',         
				' + CAST(@Balance AS VARCHAR(18)) + ',         
				' + CAST(@Fee1 AS VARCHAR(18)) + ',         
				' + CAST(@Fee2 AS VARCHAR(18)) + ',         
				' + CAST(@Fee3 AS VARCHAR(18)) + ',         
				' + CAST(@Fee4 AS VARCHAR(18)) + ',         
				' + CAST(@Discount AS VARCHAR(18)) + ',         
				''' +  CAST(@SourceID AS VARCHAR(3)) + ''',										
				''' +  CAST(@OLTransNo AS VARCHAR(10)) + ''',         
				''' + CAST(@OffTranNo AS VARCHAR(10)) + ''',         
				''' + CAST(@PosID AS VARCHAR(5)) + ''',         
				''' +  CAST(@PosTranNo AS VARCHAR(10)) + ''',         
				''' +  CAST(@PosOffTranNo AS VARCHAR(10)) + ''',         
				''' +  @Stationid + ''',         
				''' + @DeptCode + ''',         
				''' + CAST(@OperID AS VARCHAR(5)) + ''',          
				''' + @MealID  + ''',         
				' + CAST(@TaskID AS VARCHAR(5))+ ',         
				''' + @fRecKey + ''' ,  
				'''+@fExternalOrder+''' ) '         
  IF @bPRINT = 1        
  BEGIN    
   PRINT '1 ' + CAST(@MaxID AS VARCHAR(30))        
   PRINT '2 ' +  @AccountID         
   PRINT '3 ' +  @UserCardID         
   PRINT '4 ' + CAST(@PurseID AS VARCHAR(4))         
   PRINT '5 ' + CAST(@RecType AS VARCHAR(2))         
   PRINT '6 ' + CONVERT(VARCHAR(40), @CreateTime, 21)        
   PRINT '7 ' + CONVERT(VARCHAR(40), @RecvTime, 21)         
   PRINT '8 ' + CONVERT(VARCHAR(40), @SETtletime, 21)          
   PRINT '9 ' + CAST(@OldMoney AS VARCHAR(18))         
   PRINT '10 ' + CAST(@Amount AS VARCHAR(18))         
   PRINT '11 ' + CAST(@Balance AS VARCHAR(18))        
   PRINT '12 ' + CAST(@Fee1 AS VARCHAR(18))         
   PRINT '13 ' + CAST(@Fee2 AS VARCHAR(18))         
   PRINT '14 ' + CAST(@Fee3 AS VARCHAR(18))         
   PRINT '15 ' + CAST(@Fee4 AS VARCHAR(18))         
   PRINT '16 ' + CAST(@OLTransNo AS VARCHAR(10))         
   PRINT '17 ' + CAST(@OffTranNo AS VARCHAR(10))         
   PRINT '18 ' + CAST(@PosID AS VARCHAR(5))         
   PRINT '19 ' + CAST(@PosTranNo AS VARCHAR(10))        
   PRINT '20 ' + @Stationid         
   PRINT '21 ' + @DeptCode         
   PRINT '22 ' + CAST(@OperID AS VARCHAR(5))             
   PRINT '23 ' + @MealID           
   PRINT '24 ' + @fRecKey         
   PRINT '25 ' + CAST(@SourceID AS VARCHAR(5))          
            
   PRINT @TabSQL        
   SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
  END         
  EXEC sp_executesql @TabSQL
  set @ExecResult = @@ERROR 
  IF @ExecResult <> 0            
  BEGIN                     
	IF @ExecResult = 2627 
	BEGIN    
	   --重复流水 
  	  insert into T_C_REC_Repeat(fPurseID,fFlowType,fRecType,fUserCardID,fPosID,fCreateTime,fRecvTime,fAmount,fDiscount,
								 fSourceID,fTaskID,fOperID,fFee1,fFee2,fFee3,fFee4,fOffTranNo,fPosTranNo,fPosOffTranNo,ffRecKey,ffExternalOrder)
						 select  @PurseID,@FlowType,@RecType,@UserCardID,@PosID,@CreateTime,@RecvTime,@Amount,@Discount,@SourceID,
								 @TaskID,@OperID,@Fee1,@Fee2,@Fee3,@Fee4,@OffTranNo,@PosTranNo,@PosOffTranNo,@fRecKey,@fExternalOrder                      
	  SET @Ret = '3'
	  GOTO returnCommit
    END
    else   
	BEGIN         
		SET @Ret = '2'        
		GOTO returnErr        
	END 
  END

  IF @bPRINT = 1        
  BEGIN        
    PRINT '-----------判断重复插入流水_S------------'        
    SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
  END           
  SET @TabSQL=        
			   'INSERT INTO ['+@TableName_S+']         
				(fKeyID,        
				fAccountID,        
				fSerialNo,        
				fPurseID,        
				fRecType,        
				fCreateTime,        
				fRecvTime,        
				fSettleTime,        
				fOldBalance,        
				fAmount,        
				fNewBalance,        
				fFee1,        
				fFee2,        
				fFee3,        
				fFee4,        
				fDiscount,        
				fSourceID,        
				fPurseTranNo,        
				fCardTranNo,        
				fPosID,        
				fPosTranNo,        
				fPosOffTranNo,        
				fSiteID,        
				fDeptCode,        
				fOperID,        
				fMealID,        
				fTaskID,        
				fRecKey,  
				fExternalOrder)         
				VALUES(         
				''' + CAST(@MaxID AS VARCHAR(30)) + ''',         
				''' + @AccountID + ''',         
				''' + @UserCardID + ''',         
				' +  CAST(@PurseID AS VARCHAR(4)) + ',         
				''' +CAST(@RecType AS VARCHAR(2)) + ''',         
				''' + CONVERT(VARCHAR(40), @CreateTime, 21) + ''',         
				''' + CONVERT(VARCHAR(40), @RecvTime, 21) + ''',         
				''' + CONVERT(VARCHAR(40), @SETtletime, 21) + ''',         
				' + CAST(@OldMoney AS VARCHAR(18))  + ',         
				' + CAST(@Amount AS VARCHAR(18)) + ',         
				' + CAST(@Balance AS VARCHAR(18)) + ',         
				' + CAST(@Fee1 AS VARCHAR(18)) + ',         
				' + CAST(@Fee2 AS VARCHAR(18)) + ',         
				' + CAST(@Fee3 AS VARCHAR(18)) + ',         
				' + CAST(@Fee4 AS VARCHAR(18)) + ',         
				' + CAST(@Discount AS VARCHAR(18)) + ',         
				''' +  CAST(@SourceID AS VARCHAR(3)) + ''',         
				''' +  CAST(@OLTransNo AS VARCHAR(10)) + ''',         
				''' + CAST(@OffTranNo AS VARCHAR(10)) + ''',         
				''' + CAST(@PosID AS VARCHAR(5)) + ''',         
				''' +  CAST(@PosTranNo AS VARCHAR(10)) + ''',         
				''' +  CAST(@PosOffTranNo AS VARCHAR(10)) + ''',         
				''' +  @Stationid + ''',         
				''' + @DeptCode + ''',         
				''' + CAST(@OperID AS VARCHAR(5)) + ''',          
				''' + @MealID  + ''',         
				' + CAST(@TaskID AS VARCHAR(5))+ ',         
				''' + @fRecKey + ''' ,  
				'''+@fExternalOrder+''' ) '         
  IF @bPRINT = 1        
  BEGIN        
           
   PRINT '1 ' + CAST(@MaxID AS VARCHAR(30))        
   PRINT '2 ' +  @AccountID         
   PRINT '3 ' +  @UserCardID         
   PRINT '4 ' + CAST(@PurseID AS VARCHAR(4))         
   PRINT '5 ' + CAST(@RecType AS VARCHAR(2))         
   PRINT '6 ' + CONVERT(VARCHAR(40), @CreateTime, 21)        
   PRINT '7 ' + CONVERT(VARCHAR(40), @RecvTime, 21)         
   PRINT '8 ' + CONVERT(VARCHAR(40), @SETtletime, 21)          
   PRINT '9 ' + CAST(@OldMoney AS VARCHAR(18))         
   PRINT '10 ' + CAST(@Amount AS VARCHAR(18))         
   PRINT '11 ' + CAST(@Balance AS VARCHAR(18))        
   PRINT '12 ' + CAST(@Fee1 AS VARCHAR(18))         
   PRINT '13 ' + CAST(@Fee2 AS VARCHAR(18))         
   PRINT '14 ' + CAST(@Fee3 AS VARCHAR(18))         
   PRINT '15 ' + CAST(@Fee4 AS VARCHAR(18))         
   PRINT '16 ' + CAST(@OLTransNo AS VARCHAR(10))         
   PRINT '17 ' + CAST(@OffTranNo AS VARCHAR(10))         
   PRINT '18 ' + CAST(@PosID AS VARCHAR(5))         
   PRINT '19 ' + CAST(@PosTranNo AS VARCHAR(10))        
   PRINT '20 ' + @Stationid         
   PRINT '21 ' + @DeptCode         
   PRINT '22 ' + CAST(@OperID AS VARCHAR(5))             
   PRINT '23 ' + @MealID           
   PRINT '24 ' + @fRecKey         
   PRINT '25 ' + CAST(@SourceID AS VARCHAR(5))          
            
   PRINT @TabSQL        
   SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
  END         
  EXEC sp_executesql @TabSQL      
  set @ExecResult = @@ERROR
  IF @ExecResult <> 0            
  BEGIN                     
	IF @ExecResult = 2627 
	BEGIN    
	   --重复流水 
  	  insert into T_C_REC_Repeat(fPurseID,fFlowType,fRecType,fUserCardID,fPosID,fCreateTime,fRecvTime,fAmount,fDiscount,
								 fSourceID,fTaskID,fOperID,fFee1,fFee2,fFee3,fFee4,fOffTranNo,fPosTranNo,fPosOffTranNo,ffRecKey,ffExternalOrder)
						 select  @PurseID,@FlowType,@RecType,@UserCardID,@PosID,@CreateTime,@RecvTime,@Amount,@Discount,@SourceID,
								 @TaskID,@OperID,@Fee1,@Fee2,@Fee3,@Fee4,@OffTranNo,@PosTranNo,@PosOffTranNo,@fRecKey,@fExternalOrder                      
	  SET @Ret = '3'
	  GOTO returnCommit
    END
    else   
	BEGIN         
		SET @Ret = '2'        
		GOTO returnErr        
	END 
  END  
END
    
 --更新账户信息        
 IF @bPRINT = 1        
 BEGIN         
  PRINT '-----------更新账户信息------------'        
  SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime        
 END          
 IF @AccountID <> @ErrAccID --当流水为有效账户流水时才对账户进行数据更新        
 BEGIN        
  IF @RecType in (@WtCons,@WtSave,@WtTake,@WtSub,@WtLoss,@WtUnLoss,@WtMake,@WtDel,@WtRecovery,@WtChange,        
      @WtReMake,@WtOfflineWater,@WtDelNOCard,@WtCreditForLoad,@WtDebitForLoad,@WtInto,@WtOut,@WtEnabledPurse,        
      @WtSubClear,@WtAddCard)  --正常交易类数据更新        
  BEGIN           
     UPDATE T_B_Purses SET fBalance = @Balance,fTransNo = @OLTransNo  WHERE fPurseID=@fPurseID
				 IF @@ERROR <> 0            
			 	BEGIN         
							SET @Ret = '2'        
							GOTO returnErr        
				 END     
  END        
 END        
 IF  @RecType = @WtMake   
 BEGIN
    UPDATE T_B_Employee SET fCard_State=0,fSerialNo=@UserCardID WHERE fAccountID=@AccountID
	 	 IF @@ERROR <> 0            
		 	BEGIN         
						SET @Ret = '2'        
						GOTO returnErr        
			 END    
 END     

  if @RecType in (@WtPinCard,@WtDelCard)
  begin
     DELETE FROM T_B_Cards WHERE fSerialID = @UserCardID
	 	  IF @@ERROR <> 0            
		  	BEGIN         
						SET @Ret = '2'        
						GOTO returnErr        
			  END
			  if @RecType  in (@WtPinCard)
			  begin
							if exists(select  * from (select  * from  T_B_Cards where fSerialNo=@UserCardID ) a left join (select * from T_B_CardType where fIsMainCard=1) b on a.fCardTypeID=b.fCardTypeID)            
							update T_B_Employee set fCard_State=2 where fAccountID=@AccountID
     end
     else
     begin
       update T_B_Employee set fCard_State=2 where fAccountID=@AccountID
     end
     
	 	  IF @@ERROR <> 0            
		  	BEGIN         
						SET @Ret = '2'        
						GOTO returnErr        
			  END       
  end   
  else if @RecType in (@WtDel,@WtDelNOCard)--如果是撤户的就需要删除卡表数据  
  begin
     delete from T_B_Cards where  fAccountID=@AccountID
	 	  IF @@ERROR <> 0            
		  	BEGIN         
						SET @Ret = '2'        
						GOTO returnErr        
			  END               
     delete from T_B_Purses where fAccountID=@AccountID  
	 	  IF @@ERROR <> 0            
		  	BEGIN         
						SET @Ret = '2'        
						GOTO returnErr        
			  END         
     update T_B_Employee set fCard_State=4,fSerialNo='' where fAccountID=@AccountID
	 	  IF @@ERROR <> 0            
		  	BEGIN         
						SET @Ret = '2'        
						GOTO returnErr        
			  END       
  end
  

   --汇总数据        
 DECLARE @sDate    VARCHAR(20)   --入账日期        
 DECLARE @fKey_SP  VARCHAR(30)    --T_C_SUM_Pos表的关键字        
 DECLARE @fKey_SO  VARCHAR(30)   --T_C_SUM_OPER表的关键字        
 DECLARE @fKey_SE  VARCHAR(30)   --T_C_SUMEmp表的关键字        
 DECLARE @fKey_CE  VARCHAR(30)   --T_C_CashEmp表的关键字         
 DECLARE @fKey_PDR VARCHAR(30)   --T_B_PosDayRecs表的关键字
 declare @Key_Week  VARCHAR(30)  --T_C_CashEmp表类型:周
 declare @Key_Month VARCHAR(30)  --T_C_CashEmp表类型:月
 declare @Key_Year  VARCHAR(30)  --T_C_CashEmp表类型:年
 declare @where_Week varchar(30)
 declare @where_Month varchar(30)
 declare @where_Year varchar(30)
   
 set @where_Week=right('00'+cast((datepart(wk,GETDATE()) - datepart(wk,convert(varchar(7),GETDATE(),120) + '-01') + 1) as varchar(2)),2)--当月第几周
 set @where_Month=right('00'+cast(MONTH(GETDATE()) as varchar(2)),2)--月份
 set @where_Year=cast(year(GETDATE()) as varchar(4))--年份
 set @where_Week=@where_Year+@where_Month+@where_Week
 set @where_Month=@where_Year+@where_Month+'00'
 set @where_Year=@where_Year+'0000'
 set @Key_Week='01'
 set @Key_Month='02'
 set @Key_Year='03'        
 SET @sDate = CONVERT(VARCHAR(20),@SettleTime,112) --格式 20131212        
 SET @fKey_SP  = @sDate + DBO.FN_FillZero(5, @PosID)  + @MealID + DBO.FN_FillZero(2, @PurseID)               
 SET @fKey_SO  = @sDate + DBO.FN_FillZero(5, @OperID) + @MealID + DBO.FN_FillZero(2, @PurseID)          
 SET @fKey_SE  = @sDate + DBO.FN_FillZero(8, @AccountID) + DBO.FN_FillZero(2, @PurseID)         
 SET @fKey_PDR = @sDate + DBO.FN_FillZero(5, @PosID ) + DBO.FN_FillZero(2, @PurseID)           
 SET @fKey_CE  = DBO.FN_FillZero(8, @AccountID) + DBO.FN_FillZero(2, @PurseID)+@sDate+@MealID    --账号+钱包号+日期+餐次   
 SET @sDate = CONVERT(VARCHAR(20),@SettleTime,23) --格式 2013-12-12        
 
  --汇总限次
  IF @RecType IN (@WtCons, @WtOfflineWater, @WtRecovery)         
 BEGIN        
  IF @bPRINT = 1        
  BEGIN        
   PRINT '-----------汇总数据5-更新用户每日餐次消费汇总信息------------'        
   SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime        
  END               
  DECLARE @WhereUp_CE VARCHAR(180)  
  DECLARE @WhereUp_CEC VARCHAR(180) 
  DECLARE @WhereUp_CEM VARCHAR(180)           
  DECLARE @WhereInValue_CE VARCHAR(180)   
  DECLARE @WhereInValue_CEC VARCHAR(180)
  DECLARE @WhereInValue_CEM VARCHAR(180)          
  DECLARE @Symbol VARCHAR(1) 
  
  IF @RecType=@WtRecovery
	SET @Symbol='-'
  ELSE
	SET @Symbol='+'
       
  set @WhereUp_CE=''
  set @WhereUp_CEC=''
  set @WhereUp_CEM=''
  set @WhereInValue_CE=''
  set @WhereInValue_CEC=''
  set @WhereInValue_CEM=''
  
  
  --如果限次功能开启
  if @LimitCountEnabled=1
  begin  
     if  @WhereUp_CEC='' 
        set @WhereUp_CEC='fcount=fcount'+@Symbol+' 1,fcountLimit=fcountLimit '+@Symbol+' 1 '
     else
        set @WhereUp_CEC=',fcount=fcount'+@Symbol+' 1,fcountLimit=fcountLimit '+@Symbol+' 1 '
     SET @WhereInValue_CEC = ',1,1 '
  end   
  else
  begin
     if  @WhereUp_CEC=''
        set @WhereUp_CEC='fcount=fcount'+@Symbol+' 1 '
     else 
        set @WhereUp_CEC=',fcount=fcount'+@Symbol+' 1 '
     SET @WhereInValue_CEC = ',1,0 '    
  end   
  
  --如果限额功能开启
  if @LimitMoneyEnabled=1
  BEGIN
     set @WhereUp_CEM=',famount=famount '+@Symbol+ CAST(@Amount AS VARCHAR(18))+',famountLimit =famountLimit '+@Symbol+ CAST(@Amount AS VARCHAR(18))
     SET @WhereInValue_CEM = ','+CAST(@Amount AS VARCHAR(18))+','+CAST(@Amount AS VARCHAR(18))
  END
  else
  begin
     set @WhereUp_CEM=',famount=famount '+@Symbol+ CAST(@Amount AS VARCHAR(18))
     SET @WhereInValue_CEM = ','+CAST(@Amount AS VARCHAR(18))+',0'    
  end
  
  set @WhereUp_CE=@WhereUp_CEC+@WhereUp_CEM
  SET @WhereInValue_CE=@WhereInValue_CEC+@WhereInValue_CEM
  SET @WhereUp_CE=ISNULL(@WhereUp_CE,'')              
  SET @WhereInValue_CE=ISNULL(@WhereInValue_CE,'') 
  SET @TabSQL='UPDATE [T_C_CashEmp] SET '+@WhereUp_CE+' WHERE fkey= ''' + CAST(@fKey_CE AS VARCHAR(30)) + ''''         
  
  IF @bPRINT = 1        
  BEGIN        
   PRINT @TabSQL        
   SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
  END   
  DECLARE @UpdateRecCount INT      
  EXEC sp_executesql @TabSQL      
  SET @UpdateRecCount=@@rowcount        
  IF @@ERROR <> 0            
  BEGIN         
   SET @Ret = '2'    
   GOTO returnErr         
  END          
  PRINT '@UpdateRecCount - '+CAST(@UpdateRecCount AS VARCHAR(1))        
  IF @UpdateRecCount = 0         
  BEGIN 
   --插入天汇总       
   SET @TabSQL=        
    'INSERT INTO [T_C_CashEmp]         
     (fkey,        
     faccountID,        
     fdate,        
     fpurseID,        
     fmealID,
     fcount,
     fcountLimit,
     famount,
     famountLimit)         
     VALUES(         
     ''' + @fKey_CE + ''', ''' +         
     @AccountID + ''', ''' +         
     @sDate + ''', ' +          
     CAST(@PurseID AS VARCHAR(4)) + ', ''' +  
     @MealID +''''+       
     @WhereInValue_CE + ') '          
   IF @bPRINT = 1        
   BEGIN         
    PRINT @TabSQL        
    SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
   END         
   EXEC sp_executesql @TabSQL         
   IF @@ERROR <> 0            
   BEGIN         
    SET @Ret = '2'         
    GOTO returnErr         
   END 
  
  end
  

  --更新周汇总
				SET @TabSQL='UPDATE [T_C_CashEmpEx] SET '+@WhereUp_CE+' WHERE fkey= ''' + @Key_Week+DBO.FN_FillZero(8, @AccountID) + DBO.FN_FillZero(2, @PurseID)+@where_Week+@MealID + ''''         
				IF @bPRINT = 1        
				BEGIN        
					PRINT @TabSQL        
					SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
				END   
				EXEC sp_executesql @TabSQL 
				set @UpdateRecCount=@@rowcount
				IF @@ERROR <> 0            
				BEGIN         
						SET @Ret = '2'         
						GOTO returnErr            
				END
				
				if @UpdateRecCount=0
				begin
							--插入周汇总       
							SET @TabSQL=        
							'INSERT INTO [T_C_CashEmpEx]         
								(fkey, 
								ftype,       
								faccountID,        
								fvalue,        
								fpurseID,        
								fmealID,
								fcount,
								fcountLimit,
								famount,
								famountLimit)         
								VALUES(         
								''' + @Key_Week+DBO.FN_FillZero(8, @AccountID) + DBO.FN_FillZero(2, @PurseID)+@where_Week+@MealID + ''', ''' +  
								@Key_Week +''','''+      
								@AccountID + ''', ''' +         
								@where_Week + ''', ' +          
								CAST(@PurseID AS VARCHAR(4)) + ', ''' +  
								@MealID +  ''''+      
								@WhereInValue_CE + ') '          
						IF @bPRINT = 1        
						BEGIN         
							PRINT @TabSQL        
							SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
						END         
						EXEC sp_executesql @TabSQL         
						IF @@ERROR <> 0            
						BEGIN         
							SET @Ret = '2'         
							GOTO returnErr          
						END
				end
				
				--更新月汇总
				SET @TabSQL='UPDATE [T_C_CashEmpEx] SET '+@WhereUp_CE+' WHERE fkey= ''' + @Key_Month+DBO.FN_FillZero(8, @AccountID) + DBO.FN_FillZero(2, @PurseID)+@where_Month+@MealID + ''''         
				IF @bPRINT = 1        
				BEGIN        
					PRINT @TabSQL        
					SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
				END   
				EXEC sp_executesql @TabSQL  
				set @UpdateRecCount=@@rowcount       
				IF @@ERROR <> 0            
				BEGIN         
						SET @Ret = '2'         
						GOTO returnErr          
				END
				
				if @UpdateRecCount=0
				begin
								--插入月汇总       
							SET @TabSQL=        
								'INSERT INTO [T_C_CashEmpEx]         
									(fkey, 
									ftype,       
									faccountID,        
									fvalue,        
									fpurseID,        
									fmealID,
									fcount,
									fcountLimit,
									famount,
									famountLimit)         
									VALUES(         
									''' + @Key_Month+DBO.FN_FillZero(8, @AccountID) + DBO.FN_FillZero(2, @PurseID)+@where_Month+@MealID + ''', ''' +  
									@Key_Month +''','''+      
									@AccountID + ''', ''' +         
									@where_Month + ''', ' +          
									CAST(@PurseID AS VARCHAR(4)) + ', ''' +  
									@MealID +  ''''+      
									@WhereInValue_CE + ') '          
							IF @bPRINT = 1        
							BEGIN         
								PRINT @TabSQL        
								SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
							END         
							EXEC sp_executesql @TabSQL         
							IF @@ERROR <> 0            
							BEGIN         
								SET @Ret = '2'         
								GOTO returnErr         
							END
				end
				
				--更新年汇总
				SET @TabSQL='UPDATE [T_C_CashEmpEx] SET '+@WhereUp_CE+' WHERE fkey= ''' + @Key_Year+DBO.FN_FillZero(8, @AccountID) + DBO.FN_FillZero(2, @PurseID)+@where_Year+@MealID + ''''         
				IF @bPRINT = 1        
				BEGIN        
					PRINT @TabSQL        
					SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
				END   
				EXEC sp_executesql @TabSQL  
				set @UpdateRecCount=@@rowcount           
				IF @@ERROR <> 0            
				BEGIN         
						SET @Ret = '2'         
						GOTO returnErr           
				END
			 if @UpdateRecCount=0
				begin
							--插入年汇总       
							SET @TabSQL=        
								'INSERT INTO [T_C_CashEmpEx]         
									(fkey, 
									ftype,       
									faccountID,        
									fvalue,        
									fpurseID,        
									fmealID,
									fcount,
									fcountLimit,
									famount,
									famountLimit)         
									VALUES(         
									''' + @Key_Year+DBO.FN_FillZero(8, @AccountID) + DBO.FN_FillZero(2, @PurseID)+@where_Year+@MealID + ''', ''' +  
									@Key_Year +''','''+      
									@AccountID + ''', ''' +         
									@where_Year + ''', ' +          
									CAST(@PurseID AS VARCHAR(4)) + ', ''' +  
									@MealID +  ''''+      
									@WhereInValue_CE + ') '          
							IF @bPRINT = 1        
							BEGIN         
								PRINT @TabSQL        
								SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
							END         
							EXEC sp_executesql @TabSQL         
							IF @@ERROR <> 0            
							BEGIN         
								SET @Ret = '2'         
								GOTO returnErr            
							END				
  end   
  
 END 

if @RecType IN (@WtCons, @WtOfflineWater,@WtRecovery,@WtSave, @WtCreditForLoad, @WtInto, @WtMake,@WtTake, @WtDebitForLoad, @WtOut, @WtDel, @WtDelNOCard,@WtSub,@WtSubClear,
@WtLoss,@WtUnLoss,@WtRecovery,@WtChange,@WtReMake)         
 begin        
 IF @bPRINT = 1        
 BEGIN        
  PRINT '-----------汇总数据4-更新用户交易汇总信息------------'        
  SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime        
 END         
 DECLARE @TableName_SE VARCHAR(20)        
 DECLARE @WhereUp VARCHAR(400)        
 DECLARE @WhereInField VARCHAR(400)        
 DECLARE @WhereInValue VARCHAR(400)        
 EXEC SP_Wst_CheckSumEmpTable @RecvTime, @TableName_SE output        
 set @WhereUp=''        
 IF @RecType IN (@WtCons, @WtOfflineWater)         
 BEGIN        
   IF @Discount=0        
   BEGIN        
    SET @WhereUp = 'fConsCount = fConsCount + 1, fConsMoney = fConsMoney + ' + CAST(@Amount AS VARCHAR(18))  
    if @LimitCountEnabled=1    
        SET @WhereUp = @WhereUp+',fLimitConsCount = fLimitConsCount + 1, fLimitConsMoney = fLimitConsMoney + ' + CAST(@Amount AS VARCHAR(18))        
    SET @WhereInField = 'fConsCount, fConsMoney,fLimitConsCount, fLimitConsMoney'   
    if @LimitCountEnabled=1       
       SET @WhereInValue = '1, '+CAST(@Amount AS VARCHAR(18))+',1,'+ CAST(@Amount AS VARCHAR(18))+','  
    else  
       SET @WhereInValue = '1, '+CAST(@Amount AS VARCHAR(18))+',0,0,'          
   END        
   ELSE BEGIN        
    SET @WhereUp = 'fConsCount = fConsCount + 1, fConsMoney = fConsMoney + ' + CAST(@Amount AS VARCHAR(18)) +        
        ',fDiscountCount = fDiscountCount + 1, fDiscountMoney = fDiscountMoney + ' + CAST(@Discount AS VARCHAR(18))   
    if @LimitCountEnabled=1    
       SET @WhereUp = @WhereUp+',fLimitConsCount = fLimitConsCount + 1, fLimitConsMoney = fLimitConsMoney + ' + CAST(@Amount AS VARCHAR(18))            
    SET @WhereInField = 'fConsCount, fConsMoney, fDiscountCount, fDiscountMoney,fLimitConsCount, fLimitConsMoney'  
    if @LimitCountEnabled=1        
       SET @WhereInValue = '1, '+CAST(@Amount AS VARCHAR(18))+',1, '+CAST(@Discount AS VARCHAR(18))+',1,'+ CAST(@Amount AS VARCHAR(18))+','  
    else  
       SET @WhereInValue = '1, '+CAST(@Amount AS VARCHAR(18))+',1, '+CAST(@Discount AS VARCHAR(18))+',0,0,'             
   END        
 END        
 ELSE IF @RecType IN (@WtRecovery)         
 BEGIN        
  SET @WhereUp = 'fPutRightCount = fPutRightCount + 1, fPutRightMoney = fPutRightMoney + ' + CAST(@Amount AS VARCHAR(18))         
  SET @WhereInField = 'fPutRightCount, fPutRightMoney'        
  SET @WhereInValue = '1, '+CAST(@Amount AS VARCHAR(18))+','        
 END        
 ELSE IF @RecType IN (@WtSave, @WtCreditForLoad, @WtInto, @WtMake)        
 BEGIN        
  SET @WhereUp = 'fSaveCount = fSaveCount + 1, fSaveMoney = fSaveMoney + ' + CAST(@Amount AS VARCHAR(18))         
  SET @WhereInField = 'fSaveCount, fSaveMoney'        
  SET @WhereInValue = '1, '+CAST(@Amount AS VARCHAR(18))+','        
 END IF @RecType IN (@WtTake, @WtDebitForLoad, @WtOut, @WtDel, @WtDelNOCard,@WtLoss,@WtUnLoss,@WtRecovery,@WtChange,@WtReMake)        
 BEGIN        
  SET @WhereUp = 'fTakeCount = fTakeCount + 1, fTakeMoney = fTakeMoney + ' + CAST(@Amount AS VARCHAR(18))         
  SET @WhereInField = 'fTakeCount, fTakeMoney'        
  SET @WhereInValue = '1, '+CAST(@Amount AS VARCHAR(18))+','        
 END IF @RecType IN (@WtSub)        
 BEGIN        
  SET @WhereUp = 'fSubCount = fSubCount + 1, fSubMoney = fSubMoney + ' + CAST(@Amount AS VARCHAR(18))         
  SET @WhereInField = 'fSubCount, fSubMoney'        
  SET @WhereInValue = '1, '+CAST(@Amount AS VARCHAR(18))+','        
 END IF @RecType IN (@WtSubClear)        
 BEGIN        
  SET @WhereUp = 'fClearCount = fClearCount + 1, fClearMoney = fClearMoney + ' + CAST(@Amount AS VARCHAR(18))         
  SET @WhereInField = 'fClearCount, fClearMoney'        
  SET @WhereInValue = '1, '+CAST(@Amount AS VARCHAR(18))+','        
 END        
          
 SET @WhereUp=ISNULL(@WhereUp,'')        
 SET @WhereInField=ISNULL(@WhereInField,'')        
 SET @WhereInValue=ISNULL(@WhereInValue,'')        
         
 /*        
 IF @bPRINT = 1        
 BEGIN        
  PRINT @TabSQL        
  SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
 END         
 EXEC sp_executesql @TabSQL         
 IF @@ERROR <> 0            
 BEGIN         
  SET @Ret = '3'         
  GOTO returnCommit         
 END         
 */        
 if @WhereUp=''      
 set @WhereUp=' fOldBalance=fOldBalance+0 '      
 SET @TabSQL=        
  'UPDATE a          
  SET '+@WhereUp+ ', ' +         
   'fFee1 = fFee1 + '+CAST(@Fee1 AS VARCHAR(18)) + ', ' +         
   'fFee2 = fFee2 + '+CAST(@Fee2 AS VARCHAR(18)) + ', ' +         
   'fFee3 = fFee3 + '+CAST(@Fee3 AS VARCHAR(18)) + ', ' +         
   'fFee4 = fFee4 + '+CAST(@Fee4 AS VARCHAR(18)) + ', ' +         
   'a.fNewBalance = ISNULL(b.fBalance,0)'+ 
   ' from ['+@TableName_SE+'] a  '+ 
   ' LEFT JOIN T_B_Purses b on a.fAccountID=b.fAccountID and b.fPurseCode='+CAST(@PurseID as varchar(10))+      
   ' WHERE fKeyID= ''' + CAST(@fKey_SE AS VARCHAR(30)) + ''''         
 IF @bPRINT = 1        
 BEGIN        
  PRINT @TabSQL        
  SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
 END         
 EXEC sp_executesql @TabSQL               
 SET @UpdateRecCount=@@rowcount        
 IF @@ERROR <> 0            
 BEGIN         
  SET @Ret = '2'         
  GOTO returnErr         
 END          
 PRINT '@UpdateRecCount - '+CAST(@UpdateRecCount AS VARCHAR(1))        
 IF @UpdateRecCount = 0         
 BEGIN        
  SET @TabSQL=        
   'INSERT INTO ['+@TableName_SE+']         
    (fKeyID,        
    fAccountID,        
    fDate,        
    fPurseID,        
    fOldBalance,        
   '+@WhereInField+',        
    fFee1,        
    fFee2,        
    fFee3,        
    fFee4,        
    fNewBalance)         
    VALUES(         
    ''' + @fKey_SE + ''', ''' +         
    @AccountID + ''', ''' +         
    @sDate + ''', ' +          
    CAST(@PurseID AS VARCHAR(4)) + ', ' +          
    CAST(@OldMoney AS VARCHAR(18))  + ', ' +         
    @WhereInValue +           
    CAST(@Fee1 AS VARCHAR(18)) + ', ' +         
    CAST(@Fee2 AS VARCHAR(18)) + ', ' +         
    CAST(@Fee3 AS VARCHAR(18)) + ', ' +         
    CAST(@Fee4 AS VARCHAR(18)) + ', ' +            
    CAST(@Balance AS VARCHAR(18)) + ') '          
  IF @bPRINT = 1        
  BEGIN        
   PRINT '1 ' + @fKey_SE         
   PRINT '2 ' + @AccountID         
   PRINT '3 ' +  @sDate         
   PRINT '4 ' +  CAST(@PurseID AS VARCHAR(4))          
   PRINT '5 ' +  CAST(@OldMoney AS VARCHAR(18))         
   PRINT '6 ' +  @WhereInValue            
   PRINT '7 ' +  CAST(@Fee1 AS VARCHAR(18))         
   PRINT '8 ' +  CAST(@Fee2 AS VARCHAR(18))         
   PRINT '9 ' +  CAST(@Fee3 AS VARCHAR(18))         
   PRINT '10 ' +  CAST(@Fee4 AS VARCHAR(18))         
   PRINT '11 ' +  CAST(@Balance AS VARCHAR(18))         
          
   PRINT @TabSQL        
   SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime         
  END         
  EXEC sp_executesql @TabSQL         
 END        
         
 IF @@ERROR <> 0            
 BEGIN         
  SET @Ret = '2'         
  GOTO returnErr          
 END     
   
 end  
 
 --将流水写入中间表
  IF @bPrint = 1  
  BEGIN   
    PRINT '-----------将流水写入中间表T_C_middle_Step1，待后续汇总进行处理，工作站软件只处理本工作站的------------'   
  END 
  ReturnMid: 
  insert into T_C_middle_Step1 ([fPurseID],[fRecType],[fAccountID],[fUserCardID],[fPosID],[fStationID],[fMealID],[fCreateTime],
								 [fRecvTime],[fOldMoney],[fAmount],[fBalance],[fDiscount],[fOperID],[fFee1],[fFee2],[fFee3],[fFee4],[fLimitCountEnabled],
								 [fFlowType],[fSourceID],[fTaskID],[fOffTranNo],[fPosTranNo],[fPosOffTranNo],
								 [ffRecKey],[ffExternalOrder],[fIsRepeatWater],[fIsPendingConsRec])	
						values(@PurseID,@RecType,@AccountID,@UserCardID,@PosID,@StationID,@MealID,@CreateTime,
								@SettleTime,--@RecvTime,第一步需要将@SettleTime传给后面的步骤
								@OldMoney,@Amount,@Balance,@Discount,@OperID,@Fee1,@Fee2,@Fee3,@Fee4,@LimitCountEnabled,
							    @FlowType,@SourceID,@TaskID,@OffTranNo,@PosTranNo,@PosOffTranNo,
								@fRecKey,@fExternalOrder,@IsRepeatWater,@IsPendingConsRec)
  																														
         	   
 IF @@ERROR <> 0      
   GOTO returnErr          
 ReturnCommit:        
  Commit Tran        
  Return        
 ReturnErr:         
  SET @Ret = '2'        
  IF @@trancount > 0        
   Rollback Tran         
  Return        
END
go


--PROC_EDIT_15 增加存储过程UP_InsertOnLineRecord_Step2

if exists(select  * from sys.all_objects where name='UP_InsertOnLineRecord_Step2' and type='P')
drop procedure UP_InsertOnLineRecord_Step2
GO 
CREATE PROCEDURE [dbo].[UP_InsertOnLineRecord_Step2]
  @PurseID INT,      --钱包编号        
  @FlowType INT,      --流水类型        
  @RecType INT,      --交易类型        
  @UserCardID VARCHAR(16),   --用户卡号(物理卡号/应用序列号)        
  @PosID INT,       --交易终端号        
  @CreateTime DATETIME,    --交易时间        
  @RecvTime DATETIME,     --入库时间  ，为步骤1的@SettleTime      
  @Amount Numeric(18,2),    --交易额        
  @Discount Numeric(18,2),   --折扣额        
  @SourceID INT,      --来源        
  @TaskID INT,      --任务编号        
  @OperID INT,      --操作员编号         
  @Fee1 Numeric(18,2),    --其他费用1(手续费)        
  @Fee2 Numeric(18,2),    --其他费用2(卡费)        
  @Fee3 Numeric(18,2),    --其他费用3(押金)        
  @Fee4 Numeric(18,2),    --其他费用4(管理费)        
  @OffTranNo INT,      --卡脱机交易序号        
  @PosTranNo INT,      --终端联机交易序号         
  @PosOffTranNo INT,     --终端脱机交易序号        
  @fRecKey VARCHAR(200),    --数据校验Key值    
  @fExternalOrder VARCHAR(100), 
  --以下是比step1多的参数，避免再次查询
  @OldMoney Numeric(18,2),  
  @Balance Numeric(18,2),   
  @StationID varchar(10),    
  @MealID varchar(3),
  @AccountID varchar(10), 
  @LimitCountEnabled  bit,--POS机是否限次
  @IsRepeatWater INT, --是否重复流水 0-否，1-是
  @IsPendingConsRec int ,--是否是待处理流水 0-否 1-是
  @Ret int output  
      
AS        
BEGIN        
 /*常量定义(过程内值不可修改)*/        
 DECLARE        
  @WtCons INT = 0,   --联机消费         
  @WtSave INT = 1,   --存款        
  @WtTake INT = 2,   --取款        
  @WtSub  INT = 3,   --补助        
  @WtLoss INT = 4,   --挂失        
  @WtUnLoss INT = 5,   --解挂        
  @WtMake INT = 6,   --配卡/开卡/开户        
  @WtDel INT = 7,    --有卡撤户        
  @WtRecovery INT = 8,  --纠错        
  @WtChange INT = 9,   --换卡换卡        
  @WtReMake INT = 10,   --补卡补卡        
  @WtModify INT = 11,   --有卡变更        
  @WtLogin INT = 12,   --登陆        
  @WtLoginOut INT = 13,  --退出        
  @WtLoginOutErr INT = 14, --未正常退出        
  @WtRefreshBList INT = 15, --黑名单刷新        
  @WtResetPW INT = 16,  --改密码        
  @WtOfflineWater INT = 17, --脱机消费        
  @WtDelWater INT = 18,  --删除流水        
  @WtDelCons INT = 19,  --删除营业        
  @WtDelCashier INT = 20,  --删除出纳        
  @WtLossAuto INT = 21,  --自动挂失        
  @WtModifyNOCard INT = 22, --无卡变更        
  @WtFrozen INT = 23,   --人工冻结        
  @WtFrozenAuto  INT = 24, --自动冻结        
  @WtDelNOCard INT = 25,  --无卡撤户        
  @WtReissue INT = 26,  --补发卡        
  @WtUnFrozen INT = 27,  --解冻        
  @WtCreditForLoad INT = 28,  --圈存        
  @WtCreditForWrite INT = 29, --圈存补款/圈存补写卡        
  @WtDebitForLoad INT = 30,   --圈提        
  @WtPrivilege INT = 31,      --优惠        
  @WtCount INT = 32,          --计次        
  @WtInto INT = 33,           --转入        
  @WtOut INT = 34,            --转出        
  @WtDelAcc INT = 35,         --删除资料        
  @WtPinCard INT = 36,        --销卡        
  @WtSubClear INT = 37,       --补助清零          
  @WtAddCard  INT = 38,  --增加副卡        
  @WtDelCard  INT = 39,  --注销副卡        
  @WtEnabledPurse INT = 40, --启用钱包        
  @WtDisabledPurse INT = 41,  --停用钱包        
  @WtAllow INT = 90           --门禁授权        

/*过程变量定义*/        
 DECLARE                                                  
  @SettleTime DATETIME,   --入账时间        
  @Fraptime DATETIME,    --结算时间        
  @CardState INT,     --卡片状态  
  @Card_State INT,     --账户状态       
  @iSucc INT,      --写预存流水状态         
  @ErrAccID VARCHAR(20),   --无效账号 默认由原来的01999999修改为00000000        
  @ErrCardID VARCHAR(20),   --无效逻辑卡号        
  @Record_ID VARCHAR(10),         
  @TabSQL nvarchar(4000)
  
 /*临时变量定义*/        
 DECLARE         
  @PTime VARCHAR(100),        
  @bPrint BIT        
 SET @Ret = 0  --赋值返回值初始值         
 SET @bPRINT = 1  --是否显示调试信息（用于显示各个阶段耗时）         
 SET @ErrAccID = '00000000'        
 SET @ErrCardID = '00000000'           
 SET @CardState=0 
 set @Card_State=0       
 SET @SettleTime = @RecvTime  --为步骤1的@SettleTime    
 
 /*记录还原点*/        
 BEGIN TRAN       
 
 --汇总数据        
 DECLARE @sDate    VARCHAR(20)   --入账日期        
 DECLARE @fKey_SP VARCHAR(30)    --T_C_SUM_Pos表的关键字        
 DECLARE @fKey_SO  VARCHAR(30)   --T_C_SUM_OPER表的关键字        
 DECLARE @fKey_SE  VARCHAR(30)   --T_C_SUMEmp表的关键字        
 DECLARE @fKey_CE VARCHAR(30)    --T_C_ConsEmp表的关键字         
 DECLARE @fKey_PDR VARCHAR(30)   --T_B_PosDayRecs表的关键字         
         
 SET @sDate = CONVERT(VARCHAR(20),@SettleTime,112) --格式 20131212        
 SET @fKey_SP  = @sDate + DBO.FN_FillZero(5, @PosID)  + @MealID + DBO.FN_FillZero(2, @PurseID)               
 SET @fKey_SO  = @sDate + DBO.FN_FillZero(5, @OperID) + @MealID + DBO.FN_FillZero(2, @PurseID)          
 SET @fKey_SE  = @sDate + DBO.FN_FillZero(8, @AccountID) + DBO.FN_FillZero(2, @PurseID)         
 SET @fKey_PDR = @sDate + DBO.FN_FillZero(5, @PosID ) + DBO.FN_FillZero(2, @PurseID)           
 SET @fKey_CE  = @sDate + DBO.FN_FillZero(8, @AccountID) + DBO.FN_FillZero(2, @PurseID)         
 SET @sDate = CONVERT(VARCHAR(20),@SettleTime,23) --格式 2013-12-12        
 
 --如果是重复流水就写到重复流水表就可以了       
 IF @IsRepeatWater=1
 begin
 				insert into T_C_REC_Repeat(fPurseID,fFlowType,fRecType,fUserCardID,fPosID,fCreateTime,fRecvTime,fAmount,fDiscount,
															fSourceID,fTaskID,fOperID,fFee1,fFee2,fFee3,fFee4,fOffTranNo,fPosTranNo,fPosOffTranNo,ffRecKey,ffExternalOrder)
						select   @PurseID,@FlowType,@RecType,@UserCardID,@PosID,@CreateTime,@RecvTime,@Amount,@Discount,@SourceID,
															@TaskID,@OperID,@Fee1,@Fee2,@Fee3,@Fee4,@OffTranNo,@PosTranNo,@PosOffTranNo,@fRecKey,@fExternalOrder
    IF @@ERROR <> 0            
				BEGIN         
							SET @Ret = '2'               
       GOTO returnErr      
				END  
				ELSE 
				BEGIN        
								SET @Ret = '0'         
								GOTO ReturnCommit     
				END
 end
  
 --如果是待处理流水，就写到待处理流水表
 if @IsPendingConsRec=1 
 begin
				insert into T_C_PendingConsRec(fPurseID,fFlowType,fRecType, fUserCardID,fPosID,fCreateTime,fRecvTime,fAmount,fDiscount,fSourceID,       
																																		fTaskID,fOperID,fFee1,fFee2,fFee3,fFee4,fOffTranNo,fPosTranNo,fPosOffTranNo,ffRecKey,ffExternalOrder)
				values(@PurseID,@flowType,@RecType, @UserCardID,@PosID,@CreateTime,@RecvTime,@Amount,@Discount,@SourceID,       
																																		@TaskID,@OperID,@fee1,@fee2,@fee3,@fee4,@OffTranNo,@PosTranNo,@PosOffTranNo,@fRecKey,@fExternalOrder)
    IF @@ERROR <> 0            
				BEGIN         
							SET @Ret = '2'               
       GOTO returnErr      
				END  
				ELSE 
				BEGIN        
								SET @Ret = '0'         
								GOTO ReturnCommit     
				END
	end
    
 /*        
 汇总数据1-更新POS机汇总信息        
 0,1,2,3,8,17,28,29,30,31,32对这些流水进行POS机汇总        
 对这些数据类型进行POS机汇总        
 目前POS机汇总的数据中的费用类型fCType只有0这种类型        
 */ 
 declare @UpdateRecCount int        
 IF @bPRINT = 1        
 BEGIN        
  PRINT '-----------汇总数据1-更新POS机汇总信息------------'        
  SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime        
 END          
 IF ((@AccountID <> @ErrAccID) AND         
  (@RecType in (@WtCons,@WtOfflineWater))) OR         
  (@RecType in (@WtSave,@WtTake,@WtSub,@WtRecovery,@WtCreditForLoad,        
       @WtCreditForWrite,@WtDebitForLoad,@WtPrivilege,        
       @WtCount,@WtSubClear))  --消费类的账户无效不计入        
 BEGIN        
  DECLARE @CType INT        
  SET @CType = 0  --目前POS机汇总数据中只包含0这一种费用类型        
  UPDATE T_C_SUM_Pos         
  SET fMoney = fMoney + @Amount,         
   fCount = fCount + 1,         
   fDiscount = fDiscount + @Discount         
  WHERE fKey = @fKey_SP AND fTType = @RecType AND fCType = @CType and fPurseID = @PurseID  --同时判断Key、操作类型、费用类型、应用号        
   set @UpdateRecCount=@@ROWCOUNT
  IF @@error <> 0  --如果出现错误则回滚        
   GOTO returnErr
  if @UpdateRecCount=0   
   INSERT INTO [T_C_SUM_Pos]        
       ([fKey], [fPosID], [fDate], [fMealID], [fTType], [fCType], [fMoney], [fCount], [fDiscount], [fPurseID])        
   VALUES (@fKey_SP , @PosID, convert(VARCHAR(20), @SETtletime,110), @MealID, @RecType, @CType, @Amount, 1, @Discount, @PurseID)        
  IF @@error <> 0  --如果出现错误则回滚        
   GOTO returnErr        
 END        
         
         
 /*        
 汇总数据2-更新POS机流水记录收取统计表 ,注意这个不是POS汇总表         
 */        
 IF @bPRINT = 1        
 BEGIN        
  PRINT '-----------汇总数据2-更新POS机流水记录收取统计表------------'        
  SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime       END          
 IF @RecType IN (@WtCons,@WtSave,@WtTake,@WtRecovery,@WtOfflineWater) --只统计消费、存款、取款的        
 BEGIN        
  IF (@RecType = @WtSave)  --存款        
  BEGIN        
   UPDATE T_B_PosDayRecs SET fSaveCount = fSaveCount+1, fSaveSum = fSaveSum + @Amount, fLastRecTime=@SETtletime        
          WHERE fKeyID = @fKey_PDR        
   set @UpdateRecCount=@@ROWCOUNT
  IF @@error <> 0  --如果出现错误则回滚        
   GOTO returnErr
  if @UpdateRecCount=0     
    INSERT INTO T_B_PosDayRecs(fKeyID,fPosID,fRecDate,fSaveCount,fSaveSum, fLastRecTime)         
    VALUES(@fKey_PDR ,@PosID,@SETtletime,1,@Amount,@RecvTime)
  IF @@error <> 0  --如果出现错误则回滚        
   GOTO returnErr               
  END        
  ELSE IF (@RecType = @WtTake) --取款        
  BEGIN        
   UPDATE T_B_PosDayRecs SET fTakeCount = fTakeCount+1, fTakeSum = fTakeSum + @Amount, fLastRecTime=@SETtletime        
          WHERE fKeyID = @fKey_PDR        
   set @UpdateRecCount=@@ROWCOUNT
  IF @@error <> 0  --如果出现错误则回滚        
   GOTO returnErr
  if @UpdateRecCount=0        
    INSERT INTO T_B_PosDayRecs(fKeyID,fPosID,fRecDate,fTakeCount,fTakeSum, fLastRecTime)         
    VALUES(@fKey_PDR ,@PosID,@SETtletime,1,@Amount,@RecvTime) 
  IF @@error <> 0  --如果出现错误则回滚        
   GOTO returnErr          
  END          
  ELSE IF (@RecType = @WtRecovery) --纠错        
  BEGIN        
   UPDATE T_B_PosDayRecs SET fPutRightCount = fPutRightCount+1, fPutRightSum = fPutRightSum + @Amount, fLastRecTime=@SETtletime        
          WHERE fKeyID = @fKey_PDR        
   set @UpdateRecCount=@@ROWCOUNT
  IF @@error <> 0  --如果出现错误则回滚        
   GOTO returnErr
  if @UpdateRecCount=0       
    INSERT INTO T_B_PosDayRecs(fKeyID,fPosID,fRecDate,fPutRightCount,fPutRightSum, fLastRecTime)         
    VALUES(@fKey_PDR ,@PosID,@SETtletime,1,@Amount,@RecvTime)   
  IF @@error <> 0  --如果出现错误则回滚        
   GOTO returnErr           
  END          
  ELSE --0消费 17脱机消费        
  BEGIN        
   UPDATE T_B_PosDayRecs SET fRecCount = fRecCount+1, fConsSum = fConsSum + @Amount, fLastRecTime=@SETtletime        
          WHERE fKeyID = @fKey_PDR        
 set @UpdateRecCount=@@ROWCOUNT
  IF @@error <> 0  --如果出现错误则回滚        
   GOTO returnErr
  if @UpdateRecCount=0      
    INSERT INTO T_B_PosDayRecs(fKeyID,fPosID,fRecDate,fRecCount,fConsSum, fLastRecTime)        
    VALUES (@fKey_PDR ,@PosID,@SETtletime,1,@Amount,@RecvTime)
  IF @@error <> 0  --如果出现错误则回滚        
   GOTO returnErr            
  END        
 END         
          
 IF @bPRINT = 1        
 BEGIN        
  PRINT '-----------更新POS机最后更新时间------------'        
  SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime        
 END          
 UPDATE T_B_Pos SET fLastRecTime = @RecvTime WHERE fPosID = @PosID        
 IF @@error <> 0  --如果出现错误则回滚        
   GOTO returnErr         
 IF @bPRINT = 1        
 BEGIN        
  PRINT '-----------汇总数据3-更新操作员汇总信息------------'        
  SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime        
 END          
 IF @RecType IN (@WtSave,@WtTake,@WtSub,@WtLoss,@WtUnLoss,@WtMake,@WtDel,@WtRecovery,@WtChange,        
     @WtReMake,@WtModify,@WtLossAuto,@WtModifyNOCard,@WtFrozen,@WtFrozenAuto,@WtDelNOCard,@WtReissue,@WtUnFrozen,        
     @WtCreditForLoad,@WtCreditForWrite,@WtDebitForLoad,@WtPrivilege,@WtCount,@WtInto,@WtOut,        
     @WtDelAcc,@WtPinCard,@WtSubClear)        
 BEGIN        
  DECLARE @Money NUMERIC(19,2)        
  DECLARE @Count INT -- 计数次数        
  DECLARE @TType INT -- 分别对应5种费用类型 0~4        
  SET @TType = 0        
  WHILE @TType <= 4        
  BEGIN        
   SET @Money = 0.00        
   SET @Count = 0        
   IF @TType = 0   --基本费用 @TType = 0        
   BEGIN        
    SET @Count = 1            
    IF @RecType in (@WtSave,@WtTake,@WtSub,@WtLoss,@WtUnLoss,@WtRecovery,@WtChange,@WtReMake,@WtModify,        
        @WtLossAuto,@WtModifyNOCard,@WtFrozen,@WtFrozenAuto,@WtReissue,@WtUnFrozen,        
        @WtCreditForLoad,@WtCreditForWrite,@WtDebitForLoad,@WtPrivilege,@WtCount,@WtInto,@WtOut,        
        @WtDelAcc,@WtPinCard,@WtSubClear)        
     SET @Money = @Amount        
    ELSE IF @RecType = @WtMake        
     SET @Money = @Balance        
    ELSE IF @RecType in (@WtDel,@WtDelNOCard)        
     SET @Money = @OldMoney        
   END        
   ELSE IF @TType = 1 --手续费 @TType = 1        
   BEGIN        
    IF @RecType in (@WtLoss,@WtUnLoss,@WtDel,@WtChange,@WtReMake,@WtDelNOCard)        
    BEGIN        
     SET @Count = 1        
     SET @Money = @Fee1        
    END          
   else        
    goto ContinueNext        
   END        
  ELSE IF @TType = 2 --卡费 @TType = 2        
  BEGIN        
   IF @RecType in (@WtMake,@WtReMake)        
   BEGIN        
    SET @Count = 1        
    SET @Money = @Fee2        
   END        
   ELSE        
    GOTO ContinueNext        
   /*         
   IF @RecType = 6        
    SET @Money = @Fee1        
   ELSE IF @RecType = 10        
    SET @Money = @Fee4              
   */        
  END        
  ELSE IF @TType = 3 --押金 @TType = 3        
  BEGIN        
   IF @RecType in (@WtMake,@WtDel,@WtDelNOCard)        
   BEGIN        
    SET @Count = 1        
    SET @Money = @Fee3        
   END        
   ELSE        
    GOTO ContinueNext        
        
  END        
  ELSE IF @TType = 4 --管理费 @TType = 4        
  BEGIN        
   IF @RecType in (@WtSave,@WtMake,@WtCreditForLoad)        
   BEGIN        
    SET @Count = 1        
    SET @Money = @Fee4          
   END        
   ELSE        
    GOTO ContinueNext           
  END        
        
  /*当金额和数量均为0的时候，表明该操作类型不需要进行汇总或者根本就没有该费用类型，直接跳过*/        
  IF @Money = 0.00 and @Count = 0         
   GOTO ContinueNext        
  /*写汇总表中的汇总信息*/          
  UPDATE T_C_SUM_OPER         
  SET fMoney = fMoney + @Money, fCount = fCount + @Count        
  WHERE fKey = @fKey_SO  and fTType = @RecType and         
    fCType = @TType and fAppID = @PurseID  --同时判断Key、操作类型、费用类型、应用号        
 set @UpdateRecCount=@@ROWCOUNT
  IF @@error <> 0  --如果出现错误则回滚        
   GOTO returnErr
  if @UpdateRecCount=0         
   INSERT INTO T_C_SUM_OPER ( fKey, fOperID, fDate, fMealID, fTType,         
          fCType, fMoney, fCount, fAppID)        
   VALUES (@fKey_SO , @OperID, @sDate, @MealID, @RecType,        
     @TType, @Money, @Count, @PurseID )        
  IF @@error <> 0  --如果出现错误则回滚        
   GOTO returnErr        
  ContinueNext:        
   SET @TType = @TType + 1        
  END        
 END 
 
   
 --将流水写入中间表
  IF @bPrint = 1  
  BEGIN   
    PRINT '-----------将流水写入中间表T_C_middle_Step2，待后续汇总进行处理，工作站软件只处理本工作站的------------'   
  END  
  
  insert into T_C_middle_Step2 ([fPurseID],[fRecType],[fAccountID],[fPosID],[fMealID],[fRecvTime],[fOldMoney],
                                [fAmount],[fBalance],[fDiscount],[fOperID],[fFee1],[fFee2],[fFee3],[fFee4],[fLimitCountEnabled],
                                [fUserCardID],[fStationID],[fCreateTime],[fFlowType],[fSourceID],[fTaskID],
                                [fOffTranNo],[fPosTranNo],[fPosOffTranNo],[ffRecKey],[ffExternalOrder])	
																									values(@PurseID,@RecType,@AccountID,@PosID,@MealID,@RecvTime,@OldMoney,
																																@Amount,@Balance,@Discount,@OperID,@Fee1,@Fee2,@Fee3,@Fee4,@LimitCountEnabled,
																																@UserCardID,@StationID,@CreateTime,@FlowType,@SourceID,@TaskID,
                                @OffTranNo,@PosTranNo,@PosOffTranNo,@fRecKey, @fExternalOrder )

 IF @@ERROR <> 0      
   GOTO returnErr  
         
 ReturnCommit:        
  Commit Tran        
  Return        
 ReturnErr:         
  SET @Ret = '2'        
  IF @@trancount > 0        
   Rollback Tran         
  Return        
END
go

--PROC_EDIT_16 增加存储过程UP_InsertOnLineRecord_Step3


if exists(select  * from sys.all_objects where name='UP_InsertOnLineRecord_Step3' and type='P')
drop procedure UP_InsertOnLineRecord_Step3
GO 
CREATE PROCEDURE [dbo].[UP_InsertOnLineRecord_Step3]          
  @PurseID INT,      --钱包编号             
  @RecType INT,      --交易类型        
  @AccountID VARCHAR(16),--账号   
  @PosID INT,       --交易终端号        
  @MealID varchar(3),    --餐次        
  @RecvTime DATETIME,     --入库时间   为步骤1的@SettleTime 
  @OldMoney Numeric(18,2), --原余额       
  @Amount Numeric(18,2),    --交易额 
  @Balance Numeric(18,2),    --现余额       
  @Discount Numeric(18,2),   --折扣额              
  @OperID INT,      --操作员编号         
  @Fee1 Numeric(18,2),    --其他费用1(手续费)        
  @Fee2 Numeric(18,2),    --其他费用2(卡费)        
  @Fee3 Numeric(18,2),    --其他费用3(押金)        
  @Fee4 Numeric(18,2),    --其他费用4(管理费)
  @LimitCountEnabled  bit, --POS机是否限次  
  @Ret int output         
AS        
BEGIN        
 /*常量定义(过程内值不可修改)*/        
 DECLARE        
  @WtCons INT = 0,   --联机消费         
  @WtSave INT = 1,   --存款        
  @WtTake INT = 2,   --取款        
  @WtSub  INT = 3,   --补助        
  @WtLoss INT = 4,   --挂失        
  @WtUnLoss INT = 5,   --解挂        
  @WtMake INT = 6,   --配卡/开卡/开户        
  @WtDel INT = 7,    --有卡撤户        
  @WtRecovery INT = 8,  --纠错        
  @WtChange INT = 9,   --换卡换卡        
  @WtReMake INT = 10,   --补卡补卡        
  @WtModify INT = 11,   --有卡变更        
  @WtLogin INT = 12,   --登陆        
  @WtLoginOut INT = 13,  --退出        
  @WtLoginOutErr INT = 14, --未正常退出        
  @WtRefreshBList INT = 15, --黑名单刷新        
  @WtResetPW INT = 16,  --改密码        
  @WtOfflineWater INT = 17, --脱机消费        
  @WtDelWater INT = 18,  --删除流水        
  @WtDelCons INT = 19,  --删除营业        
  @WtDelCashier INT = 20,  --删除出纳        
  @WtLossAuto INT = 21,  --自动挂失        
  @WtModifyNOCard INT = 22, --无卡变更        
  @WtFrozen INT = 23,   --人工冻结        
  @WtFrozenAuto  INT = 24, --自动冻结        
  @WtDelNOCard INT = 25,  --无卡撤户        
  @WtReissue INT = 26,  --补发卡        
  @WtUnFrozen INT = 27,  --解冻        
  @WtCreditForLoad INT = 28,  --圈存        
  @WtCreditForWrite INT = 29, --圈存补款/圈存补写卡        
  @WtDebitForLoad INT = 30,   --圈提        
  @WtPrivilege INT = 31,      --优惠        
  @WtCount INT = 32,          --计次        
  @WtInto INT = 33,           --转入        
  @WtOut INT = 34,            --转出        
  @WtDelAcc INT = 35,         --删除资料        
  @WtPinCard INT = 36,        --销卡        
  @WtSubClear INT = 37,       --补助清零          
  @WtAddCard  INT = 38,  --增加副卡        
  @WtDelCard  INT = 39,  --注销副卡        
  @WtEnabledPurse INT = 40, --启用钱包        
  @WtDisabledPurse INT = 41,  --停用钱包        
  @WtAllow INT = 90           --门禁授权        
        
 --此处内容填写第三方数据，比如说短信发送表，第三方消费推送表等
 
 SET @Ret = 0  --赋值返回值初始值  
 return
              
END
go 

--PROC_EDIT_17 增加存储过程UP_MakeSumEmpByday



if exists(select * from dbo.sysobjects where name='UP_MakeSumEmpByday' and type='P')
   drop procedure [dbo].[UP_MakeSumEmpByday]
go   
--EXEC UP_MakeSumEmpByday '2021-06-03'
create procedure UP_MakeSumEmpByday
  @Date nvarchar(10)     --格式：2018-08-08 
as
begin
  DECLARE @Month varchar(6),
										@TableName varchar(20),
										@LastTableName varchar(20),
										@sql nvarchar(4000),
										@CurDate datetime,
										@LastDate nvarchar(10),
										@TableName_CE varchar(30) ,
          @NowDate varchar(10),
          @AccountID varchar(10),
          @PurseID int,
          @RecCount int,
          @KeyID varchar(20),
          @PurseEnable int, 
          @PurseEnableDate datetime,
          @PurseLastNewBalance numeric(9,2)
             
  set @Month=SUBSTRING(@Date,1,4)+SUBSTRING(@Date,6,2)
  set @TableName='T_C_SumEmp_'+@Month
  set @LastTableName=''
  set @CurDate=Convert(datetime,@Date,120)
  set @NowDate=CONVERT(varchar(10),GETDATE(),120)
  if NOT EXISTS(SELECT  * FROM SYS.all_objects WHERE name='T_B_AccountIDTmp')
  
  CREATE TABLE T_B_AccountIDTmp
  (fAccountID varchar(20))
		/*利用游标生成动态sql语句,自动创建月表视图*/
		select name,IDENTITY(int,1,1) as Nid into #t1 from sysobjects  where name like 'T_c_SumEmp_20%' and LEN(name)=17 ORDER BY name --把月表名称查询出来保存到临时表,在查询结果中添加自增列
		declare t_cursor cursor for 
		select name,nid from #t1
		open t_cursor
		declare @t_name varchar(100),@a int,@sql1 varchar(7000),@sql2 varchar(7000),@sql3 varchar(7000),@sql4 varchar(7000)
		set @sql2='select * from '
		set @sql4='if exists (select * from dbo.sysobjects where id = object_id(N''[dbo].[VIEW_SUMEmpRec]'') and OBJECTPROPERTY(id, N''IsView'') = 1) drop view [dbo].[VIEW_SUMEmpRec]'
		set @sql3='create view [dbo].[VIEW_SUMEmpRec] as '
		fetch next from t_cursor into @t_name,@a
		while  @@Fetch_Status=0 
				begin 
						if @a=1
						begin  
								set @sql1=@sql2+@t_name   
								set @sql3=@sql3+@sql1
						end
						else
						begin
								set @sql1=' union all '+char(13)+@sql2+@t_name   
								set @sql3=@sql3+@sql1
						end
						fetch next from t_cursor into @t_name,@a
				end    
		close t_cursor
		deallocate t_cursor
		exec(@sql4)      ---判断视图是否存在,如果存在就先删除
		exec(@sql3)      ---建视图
		--print @sql3      ---可以查询sql语句是否正确
		drop table #t1   ---删除临时表


  /*
     先建立一张表，用来保存哪些天的数据已经被处理的，已经处理的数据不用再次处理
     1、判断日期，日过不大于当前日期才进行操作
     2、按人员、钱包分组取前一天的现余额作为日期@Date 的原余额和现余额
     3、将数据写入个人每日结余表
  */
 
  
  --如果传进来的日期超过当天，就退出
  if @NowDate>=@Date 
  begin 
     EXEC SP_Wst_CheckConsEmpTable @CurDate, @TableName_CE output
     
     /******************钱包循环****************/ 
     declare  cur_Purse cursor for  
     SELECT fPurseCode  FROM T_B_PurseCode where fState=1  
     open cur_Purse    
     fetch next  from cur_Purse into @PurseID  
     while @@fetch_status=0    
     begin 
							--取每个人钱包号为@PurseID的第一条(用来判断钱包是否开通以及开通时间)，也就是最早的一条，在最早一条之前的都不用补，因为还没开通钱包
							select t.* into #PurseFirstRecord from
							(select *,row_number() over (partition by fAccountID order by fDate) rn 
							from (select * from VIEW_SUMEmpRec where fPurseID=@PurseID )tt) t
							where rn=1
							--取每个人指定日期，指定钱包最后一条交易记录(用来获取上一笔的现余额，用于作为补流水的原余额)
								select t.* INTO #PurseLastRecord  from
							(select *,row_number() over (partition by fAccountID order by fDate desc ) rn 
							from (select * from VIEW_SUMEmpRec where fPurseID=@PurseID  and CONVERT(VARCHAR(10),fDate,120)<@Date)tt) t
							where rn=1
							/******************账号循环****************/
							truncate table T_B_AccountIDTmp 
							SET @SQL='insert into T_B_AccountIDTmp SELECT distinct fAccountID   FROM '+ @TableName +' where fPurseID='+CAST(@PurseID as varchar(2))+' AND CONVERT(VARCHAR(10),fDate,120)='''+@Date+''''   
							PRINT @SQL
							EXEC(@SQL)
							declare  cur_AccountID cursor for  
										select  a.fAccountID,(case when ISNULL(b.fAccountID,'')='' THEN 0 ELSE 1 END )PurseEnable ,b.fDate,c.fNewBalance  
																		from T_B_Employee a  
																		left join #PurseFirstRecord b on a.fAccountID=b.fAccountID
																		left join #PurseLastRecord c on a.fAccountID=c.fAccountID
										where a.fCard_State<>3 AND a.fAccountID NOT IN (SELECT fAccountID from T_B_AccountIDTmp) 
									 order by a.fAccountID  
							open cur_AccountID    
							fetch next  from cur_AccountID into @AccountID,@PurseEnable,@PurseEnableDate,@PurseLastNewBalance  
							while @@fetch_status=0    
							begin  
												--如果开通了钱包才需要补
												if @PurseEnable=1
												begin
															--如果指定日期小于了钱包首次开通的日期，就不需要补
															if convert(varchar(10),@PurseEnableDate,120)<=@Date
															begin							               
																			--补一条数据
																			set @KeyID= CONVERT(VARCHAR(20),@CurDate,112) + DBO.FN_FillZero(8, @AccountID) + DBO.FN_FillZero(2, @PurseID)         
																			set @sql=' INSERT INTO '+@TableName+'(fKeyID,fAccountID,fDate,fPurseID,
																														fOldBalance,fConsCount,fConsMoney,fLimitConsCount,fLimitConsMoney,fSaveCount,fSaveMoney,
																														fTakeCount,fTakeMoney,fSubCount,fSubMoney,fClearCount,fClearMoney,fPutRightCount,fPutRightMoney,
																														fDiscountCount,fDiscountMoney,fFee1,fFee2,fFee3,fFee4,fNewBalance)
																														values('''+@KeyID+''','''+@AccountID+''','''+@Date+''','+CAST(@PurseID as varchar(2))+','+
																														CAST(@PurseLastNewBalance as varchar(10))+',0,0.00,0,0.00,0,0.00,'+
																														'0,0.00,0,0.00,0,0.00,0,0.00,'+
																														'0,0.00,0,0.00,0,0.00,'+CAST(@PurseLastNewBalance as varchar(10))+')'
																			exec(@sql)
															end
												end
									fetch next from cur_AccountID into  @AccountID,@PurseEnable,@PurseEnableDate,@PurseLastNewBalance   
							end  
							close cur_AccountID  
							deallocate  cur_AccountID
       /******************账号循环结束****************/ 
       drop table #PurseFirstRecord
       drop table #PurseLastRecord
       fetch next from cur_Purse into  @PurseID   
     end  
     close cur_Purse  
     deallocate  cur_Purse  
     /******************钱包循环结束****************/ 
  end
  
  if exists(select  * from T_C_SumEmpDealByDay   where fDate=@Date)
     update T_C_SumEmpDealByDay set fCreateTime=GETDATE(),fOpreID=99999 where fDate=@Date
  else
     insert INTO T_C_SumEmpDealByDay(fDate,fCreateTime,fOpreID)VALUES(@Date,GETDATE(),99999)
     
end
go

--PROC_EDIT_18 增加存储过程UP_RecordBAWList
if exists(select * from dbo.sysobjects where name='UP_RecordBAWList' and type='P')
   drop procedure [dbo].[UP_RecordBAWList]
go  

create procedure [dbo].[UP_RecordBAWList] @fAccountID varchar(18),  
  @fCardNo varchar(20),  
  @fPhysicalNo varchar(20),  
  @fPosID int,           --0表示所有 >0表示对应的机号  
  @fOperType varchar(2), --A:增加 D:删除 S:标记  
  @fListType varchar(2), --0:CB消费黑名单 1:CW消费白名单 2:AW考勤白名单 3:EW门禁白名单 其他无效  
  @fRemark varchar(20)   --备注   
    as  
BEGIN  
 if @fListType not in ('CB','AW','EW','CW') Return  
 if @fOperType not in ('A','D','S') Return  
 if LEN(@fCardNo)<6 Return  
 if (LEN(@fPhysicalNo)<6) and (@fListType in ('EW')) Return   --'AW',  
    
 if @fListType = 'CB' --消费黑名单  
 begin  
  if @fPosID = 0 --0代表所有POS机，需要将原来对应的卡号的fIsUsed全部置为false    
  begin  
    UPDATE T_L_CBlack SET fIsUsed = 0   
   WHERE fAccountID = @fAccountID and fCardNo = @fCardNo  
  end  
  else  
  begin  
    UPDATE T_L_CBlack SET fIsUsed = 0   
   WHERE fPosID = @fPosID and fAccountID = @fAccountID and fCardNo = @fCardNo   
  end  
  INSERT INTO T_L_CBlack  
      (fAccountID, fCardNo, fPhysicalNo, fPosID, fOperType, fIsUsed, fRemark)  
   VALUES  
      (@fAccountID,@fCardNo,@fPhysicalNo,@fPosID,@fOperType,1,@fRemark)  
 end  
 else if @fListType = 'AW' --考勤白名单  
 begin  
  if @fPosID = 0 --0代表所有POS机，需要将原来对应的卡号的fIsUsed全部置为false    
  begin  
    UPDATE T_L_AWhite SET fIsUsed = 0   
   WHERE fAccountID = @fAccountID and fCardNo = @fCardNo --and fPhysicalNo = @fPhysicalNo  
  end  
  else  
  begin  
    UPDATE T_L_AWhite SET fIsUsed = 0   
   WHERE fPosID = @fPosID and fAccountID = @fAccountID and fCardNo = @fCardNo --and fPhysicalNo = @fPhysicalNo  
  end  
  INSERT INTO T_L_AWhite  
      (fAccountID, fCardNo, fPhysicalNo, fPosID, fOperType, fIsUsed, fRemark)  
   VALUES  
      (@fAccountID,@fCardNo,@fPhysicalNo,@fPosID,@fOperType,1,@fRemark)  
 end  
 else if @fListType = 'EW' --门禁白名单  
 begin  
  if @fPosID = 0 --0代表所有POS机，需要将原来对应的卡号的fIsUsed全部置为false    
  begin  
    UPDATE T_L_EWhite SET fIsUsed = 0  
   WHERE fAccountID = @fAccountID and fCardNo = @fCardNo and fPhysicalNo = @fPhysicalNo  
  end  
  else  
  begin  
    UPDATE T_L_EWhite SET fIsUsed = 0  
   WHERE fPosID = @fPosID and fAccountID = @fAccountID and fCardNo = @fCardNo and fPhysicalNo = @fPhysicalNo  
  end  
  INSERT INTO T_L_EWhite  
      (fAccountID, fCardNo, fPhysicalNo, fPosID, fOperType, fIsUsed, fRemark)  
   VALUES  
      (@fAccountID,@fCardNo,@fPhysicalNo,@fPosID,@fOperType,1,@fRemark)  
 end  
 else if @fListType = 'CW' --消费白名单  
 begin  
  if @fPosID = 0 --0代表所有POS机，需要将原来对应的卡号的fIsUsed全部置为false    
  begin  
    UPDATE T_L_CWhite SET fIsUsed = 0   
   WHERE fAccountID = @fAccountID and fCardNo = @fCardNo  
  end  
  else  
  begin  
    UPDATE T_L_CWhite SET fIsUsed = 0   
   WHERE fPosID = @fPosID and fAccountID = @fAccountID and fCardNo = @fCardNo   
  end  
  INSERT INTO T_L_CWhite  
      (fAccountID, fCardNo, fPhysicalNo, fPosID, fOperType, fIsUsed, fRemark)  
   VALUES  
      (@fAccountID,@fCardNo,@fPhysicalNo,@fPosID,@fOperType,1,@fRemark)  
 end 
 
END  
GO


--REPORT_ADD_1 新增身份消费统计报表UP_Report_Cns_Total_ManTypeMeal

if exists(select * from dbo.sysobjects where name='UP_Report_Cns_Total_ManTypeMeal' and type='P')
   drop procedure [dbo].[UP_Report_Cns_Total_ManTypeMeal]
go   
create procedure [dbo].[UP_Report_Cns_Total_ManTypeMeal]
  @StationID varchar(2),
  @BeginTime datetime,
  @EndTime datetime,
  @ManType varchar(280),
  @Meal varchar(120),
  @PosID varchar(1200)
as
begin 				
		declare @sBeginDateTime varchar(19)
		declare @sEndDateTime varchar(19)
		declare @sBeginNY varchar(6)
		declare @sEndNY varchar(6)
		declare @RecCount int
		declare @i int
		declare @TableName varchar(15)
		declare @MealID varchar(3)
		declare @MealName varchar(20)
		declare @SqlStr nvarchar(max)=''
		declare @SqlStr1 nvarchar(1000)=''
		declare @SqlStr2 nvarchar(2000)=''	
		declare @sDataSet varchar(2000)=''
				
		set @sBeginDateTime=CONVERT(varchar(10),@BeginTime,120) + ' 00:00:00'
		set @sEndDateTime=CONVERT(varchar(10),@EndTime,120) + ' 23:59:59'
		set @sBeginNY=CONVERT(varchar(6),@BeginTime,112)
		set @sEndNY=CONVERT(varchar(6),@EndTime,112)				
				
		select identity(int,1,1) id,name into #ls_Tb from dbo.sysobjects 
			where name like '%T_C_RECS_20%' and type='U' --这里只取S表，如果要处理C表，则应为：'%T_C_RECC_20%'
					and substring(Name,10,6) >= @sBeginNY and substring(Name,10,6)<=@sEndNY
					and LEN(name)=15
			order by name	   
		select @RecCount=COUNT(*) from #ls_Tb
		if @RecCount=0 
		begin
				select '没有该时间段内的数据表'
				drop table #ls_Tb
				return
		end
				
		set @i=1
		set @sDataSet=''
		while @i<=@RecCount
		begin
				select @TableName=name from #ls_Tb where id=@i
				if @i=@RecCount
							set @sDataSet=@sDataSet + 'select * from ' + @TableName 
				else
							set @sDataSet=@sDataSet + 'select * from ' + @TableName + CHAR(13) + ' union all ' +CHAR(13)
				set @i=@i+1             
		end
		set @sDataSet='('+@sDataSet+') as R'
		
		drop table #ls_Tb
		--print @sDataSet
		--return
		select IDENTITY(int,1,1) id,* into #ls_Ml from T_B_MealSet
		select @RecCount=COUNT(*) from T_B_MealSet
		IF @RecCount=0 
		begin
				select '没有餐次数据'
				return
		end
		
		set @SqlStr1 = ' select a.fId_TypeName [身份类型],a.fPosID [机号],a.fPosName [设备名称],'+CHAR(10)
		
		set @i=1
		while @i<=@RecCount
		begin
		  select @MealID=fMeal_Id, @MealName=fMeal_Name from #ls_Ml where id=@i
		  
		  set @SqlStr1 = @SqlStr1 + 'sum(case A.fMealID  when '''+@MealID+''' then 1 else 0 end) as ['+	@MealName+'|次数], 
		                             sum(case A.fMealID  when '''+@MealID+''' then A.fAmount else 0 end) as ['+	@MealName+'|金额],'	+CHAR(10)

		  set @i=@i+1
		end
		drop table #ls_Ml
		set @SqlStr1=@SqlStr1+'sum(A.fAmount) as [合计|消费金额] from ('      
		set @SqlStr = ' select T.fId_TypeName,R.fPosID+''号机'' fPosID, P.fPosName,R.fMealID, r.fAmount from ' + @sDataSet +'
		                 left join T_B_Employee E on r.fAccountID=E.fAccountID
		                 left join T_B_ManType T on E.fId_TypeId=T.fId_TypeId
		                 left join T_B_MealSet M on R.fMealID = M.fMeal_Id
		                 left join V_B_SitePos P on R.fPosID=P.fPosId
		                 where fRecType in (0, 17) and fCreateTime>='''+@sBeginDateTime +''' and fCreateTime <='''+ @sEndDateTime + ''''+CHAR(10)+CHAR(13)
		                 
		if len(@ManType)>8
		begin
		  set @SqlStr = @SqlStr + 'and '+ @ManType+CHAR(10)+CHAR(13)
		end
		
		if LEN(@Meal)>6
		begin
		  set @SqlStr = @SqlStr + 'and '+ @Meal+CHAR(10)+CHAR(13)
		end 
		
		if LEN(@PosID)>6
		begin
		  set @SqlStr = @SqlStr + 'and '+ @PosID
		end                 
		
		set @SqlStr2=') A group by a.fId_TypeName ,a.fPosID ,a.fPosName 
		                  order by a.fId_TypeName ,a.fPosID '
		set @SqlStr = @SqlStr1+@SqlStr+@SqlStr2
		--print @sqlstr
		exec(@SqlStr)

end
go

--REPORT_ADD_2 新增营业分组报表 UP_Report_Cns_Total_DeptBZ

if exists(SELECT  * FROM SYS.all_objects WHERE name='UP_Report_Cns_Total_DeptBZ' AND type='P')
drop procedure UP_Report_Cns_Total_DeptBZ
go
--exec UP_Report_Cns_Total_DeptBZ '','2020-06-01','2020-06-30',''
create procedure [dbo].[UP_Report_Cns_Total_DeptBZ]        
  @Station     varchar(20),  -- 工作站；传值，工作站名称，只能传入一个工作站名称        
  @BegDateTime varchar(20),  --开始查询日期        
  @EndDateTime varchar(20),  --结束查询日     
  @St_Ids varchar(4000),       --区域码组合
  @PurseTypeStr varchar(400)  --钱包选择
as        
        
BEGIN        
 declare @STRSQL varchar(8000),        
   @iRet int,        
   @sRet varchar(300),        
   @strB varchar(30),        
   @strE varchar(30),
   @i int ,
   @stwhere varchar(4000)       
 SET @strB = CONVERT(varchar(20), @BegDateTime, 23) + ' 00:00:00'        
 SET @strE = CONVERT(varchar(20), @EndDateTime, 23) + ' 23:59:59'         
 EXEC UP_R_CheckTime @strB, @strE, 1, @iRet output, @sRet output        
 if @iRet = -9999 OR @sRet = ''        
 begin        
  if @iRet = -9999        
    SET @STRSQL = 'SELECT ''查询表无效-查询表范围超期'' AS [返回信息]'        
     else if @sRet = ''        
       SET @STRSQL = 'SELECT ''查询表无效-查询范围内没有流水产生'' AS [返回信息]'        
     else        
       SET @STRSQL = 'SELECT ''查询表无效-无法确定的原因'' AS [返回信息]'          
  --print @STRSQL           
  exec(@STRSQL)        
  Return        
 end         
         
 set @i=0
         
 set @STRSQL =         
 'select r.fDeptCode,sum(case when fRecType in(0,17) then  fAmount else 0 end ) as fAmount,      
 sum( case when fRecType in(0,17) then 1 else 0 end ) as fPosFare_Count,      
 sum(case when fRecType in(8) then  fAmount else 0 end ) as fjcCons_Fare,
 sum( case when fRecType in(8) then 1 else 0 end ) as fjcPosFare_Count,       
 fBz_Id,fBz_Name into #temp1 From ' +          
 @sRet +CHAR(13)+         
 'inner join T_B_Pos p on r.fPosid=p.fPosID        
  inner join T_B_Bzbm b on p.fSiteID=b.fBz_Id        
  inner join T_B_Dept d on d.fDeptCode=r.fDeptCode        
  where fRecType in(0,8,17)'+        
   ' and R.fSettleTime >= ''' + @strB + ''' AND R.fSettleTime <= ''' +@strE + '''          
   and (r.fSiteId like ''' + @Station + '%'')  '+ char(13)     
 if @St_Ids<>''     
    set @STRSQL= @STRSQL+'   and '+ @St_Ids+  char(13)
 if  @PurseTypeStr<>''
   set @STRSQL = @STRSQL+ ' and '+@PurseTypeStr+  char(13)
 set @STRSQL=@STRSQL+' group by r.fDeptCode,fBz_Id,fBz_Name   '    
     
  --以下按客户要求，只统计出选择的营业组 modify by Tan 2016.09.07    
  select  fBz_Id,fBz_Name into #temp2 from T_B_Bzbm where 1=2    
  if @St_Ids=''    
     insert #temp2(fBz_Id,fBz_Name)    
     select fBz_Id,fBz_Name from T_B_Bzbm     
  else    
     insert #temp2(fBz_Id,fBz_Name)    
     select fBz_Id,fBz_Name from T_B_Bzbm     
      where CHARINDEX(fBz_Id,@St_Ids)>0       
   --以上按客户要求，只统计出选择的营业组 modify by Tan 2016.09.07      
if @St_Ids=''
set @stwhere='' 
else
set @stwhere=' and '+ @St_Ids

set @STRSQL = @STRSQL +
             'SELECT 营业组名称,消费次数,消费金额,纠错次数,纠错金额,实际消费次数,实际消费金额,签字 FROM ('+  
													'select b.fbz_id as ''营业组编号'' ' + char(13)+   
													',b.fbz_Name AS ''营业组名称''' + char(13)+  
													',sum(isnull(fPosFare_Count,0)) as ''消费次数''' + char(13)+  
													',sum(isnull(fAmount,0)) as ''消费金额'' ' + char(13)+  
													',sum(isnull(fjcPosFare_Count,0)) as ''纠错次数''' + char(13)+   
													',sum(isnull(fjcCons_Fare,0)) as ''纠错金额'' ' + char(13)+ 
													',sum(isnull(fPosFare_Count,0))-sum(isnull(fjcPosFare_Count,0)) as ''实际消费次数''' + char(13)+   
														',sum(isnull(fAmount,0))-sum(isnull(fjcCons_Fare,0)) as ''实际消费金额'' ' + char(13)+   
													' ,'''' as [签字]' + char(13)+   
													'from #temp1 a right join T_B_Bzbm b on  a.fBz_Id=b.fBz_Id where 1=1 '+@stwhere+  
													'group by b.fbz_id,b.fbz_Name) T' 
          
print @STRSQL        
 exec(@STRSQL)        
END 
go


--REPORT_ADD_3 新增菜品流水汇总UP_Report_Cns_DishRecSum

if exists(select  * from sys.all_objects where name='UP_Report_Cns_DishRecSum' and type='P')
drop procedure UP_Report_Cns_DishRecSum
GO 
-- exec UP_Report_Cns_DishRecSum '','2020-12-17','2020-12-17','',''
create procedure [dbo].[UP_Report_Cns_DishRecSum] @STATIONID    VARCHAR(20),     -- 工作站；传值，工作站名称，只能传入一个工作站名称        
   @BeginDate     datetime,       --开始时间        
   @EndDate       datetime,       --结束时间          
   @DishIDstr     varchar(1000),  --菜品编号        
   @Bzstr         varchar(1000)   --班组         
as        
begin         
 declare @SQL           nvarchar(4000)    
 declare @SQLSTR  nvarchar(4000)      
 declare @DateStr    varchar(100)        
 declare @BzSQL     varchar(4000)        
 declare @DishStr    varchar(4000)        
 declare @monthDiff     int        
 declare @iRet   int        
 declare @sRet   varchar(300)        
 set @BeginDate=Cast(@BeginDate as varchar(10))+' 00:00:00'          
 set @EndDate=Cast(@EndDate as varchar(10))+' 23:59:59'         
         
         
 EXEC UP_R_CheckTime @BeginDate, @EndDate, 6, @iRet output, @sRet output        
 if @sRet = '' or @iRet = -9999        
 begin        
      SELECT '查询表无效-查询表范围超期' AS [返回信息]         
   Return --如果表不存在，直接退出        
 end        
         
 select @monthDiff=ltrim(datediff(yy,@BeginDate,@EndDate))*12+ltrim(datediff(mm,@BeginDate,@EndDate)%12)        
         
 if @monthDiff >1         
 begin        
   select '可选择时间段跨度最大为2个自然月' as 查询结果        
   return        
 end         
         
 SET @DateStr='fRecordedTime>='''+convert(varchar(20), @BeginDate, 120 )+''' AND fRecordedTime<='''+convert(varchar(20), @EndDate, 120 )+''''        
         
 IF @DishIDstr=''        
  SET @DishStr=''        
 ELSE        
  SET @DishStr=' AND '+@DishIDstr        
          
 IF @Bzstr=''        
 BEGIN        
  SET @BzSQL=''        
  SET @SQL = 'SELECT R.fDishID AS 菜品编号, H.fDishName AS 菜品名称, R.fDishPrice AS 菜品单价, sum(fDishCount) AS 菜品数量, R.fDishPrice*sum(fDishCount) AS 合计  FROM ' + @sRet +        
  ' LEFT JOIN T_B_Dish H ON H.fDishID=R.fDishID '+        
  ' WHERE '+@DateStr+@DishStr+        
  ' GROUP BY R.fDishID, H.fDishName,R.fDishPrice '+        
  ' ORDER BY R.fDishID'        
 END        
 ELSE BEGIN        
  SET @BzSQL=' AND '+@Bzstr        
  SET @SQL = 'SELECT D.fBz_Name AS 班组名称 , R.fDishID AS 菜品编号, H.fDishName AS 菜品名称, R.fDishPrice AS 菜品单价, sum(fDishCount) AS 菜品数量, R.fDishPrice*sum(fDishCount) AS 合计  FROM '+ @sRet +        
  ' LEFT JOIN T_B_Dish H ON H.fDishID=R.fDishID '+        
  ' LEFT JOIN T_B_Pos P ON P.fPosID=R.fPosID '+        
  ' INNER JOIN T_B_Bzbm D ON D.fBz_Id=P.fSiteID '+        
  ' WHERE '+@DateStr+@BzSQL+@DishStr+        
  ' GROUP BY R.fDishID, H.fDishName,R.fDishPrice,D.fBz_Name        
  ORDER BY D.fBz_Name,R.fDishID'        
 END     
 
 PRINT @SQL        
 EXEC(@SQL)  
end   
GO


--REPORT_ADD_4 新增菜品流水明细UP_Report_Cns_DishRecDetail
if exists(select  * from sys.all_objects where name='UP_Report_Cns_DishRecDetail' and type='P')
drop procedure UP_Report_Cns_DishRecDetail
GO 
-- exec UP_Report_Cns_DishRecDetail '','2020-12-17','2020-12-17','',''
create procedure [dbo].[UP_Report_Cns_DishRecDetail] @STATIONID    VARCHAR(20),     -- 工作站；传值，工作站名称，只能传入一个工作站名称        
   @BeginDate     datetime,       --开始时间        
   @EndDate       datetime,       --结束时间          
   @DishIDstr     varchar(1000),  --菜品编号        
   @Bzstr         varchar(1000)   --班组         
as        
begin         
 declare @SQL           nvarchar(4000)    
 declare @SQLSTR  nvarchar(4000)      
 DECLARE @WHERE VARCHAR(4000)     
 declare @monthDiff     int        
 declare @iRet   int        
 declare @sRet   varchar(300)        
 set @BeginDate=Cast(@BeginDate as varchar(10))+' 00:00:00'          
 set @EndDate=Cast(@EndDate as varchar(10))+' 23:59:59'         
       
 EXEC UP_R_CheckTime @BeginDate, @EndDate, 6, @iRet output, @sRet output        
 if @sRet = '' or @iRet = -9999        
 begin        
      SELECT '查询表无效-查询表范围超期' AS [返回信息]         
   Return --如果表不存在，直接退出        
 end        
         
 select @monthDiff=ltrim(datediff(yy,@BeginDate,@EndDate))*12+ltrim(datediff(mm,@BeginDate,@EndDate)%12)        
         
 if @monthDiff >1         
 begin        
   select '可选择时间段跨度最大为2个自然月' as 查询结果        
   return        
 end         
         
 SET @WHERE='R.fRecordedTime>='''+convert(varchar(20), @BeginDate, 120 )+''' AND R.fRecordedTime<='''+convert(varchar(20), @EndDate, 120 )+''''        
 IF @DishIDstr<>''
 SET @WHERE =@WHERE +' AND '+@DishIDstr       
 IF @Bzstr<>''
 SET @WHERE =@WHERE +' AND '+@Bzstr         
          
 SET @SQL ='SELECT 	E.fName 姓名,
																				R.fAccountID 账号,
																				F.fDeptName 部门,
																				B.fDishName 菜品名称,
																				R.fDishID 菜品编号,
																				R.fDishCount 菜品数量,
																				R.fDishPrice 菜品单价,
																				R.fRecordedTime 消费时间,
																				R.fPosID 机号,
																				C.fPosName 设备名称,
																				D.fBz_Name 班组名称 FROM '+@sRet+'  
																				LEFT JOIN T_B_Dish B ON R.fDishID=B.fDishID
																				LEFT JOIN T_B_Pos C ON R.fPosID=C.fPosID
																				LEFT JOIN  T_B_Bzbm D ON D.fBz_Id=C.fSiteID
																				LEFT JOIN T_B_Employee E ON R.fAccountID=E.fAccountID 
																				LEFT JOIN T_B_Dept F ON E.fDept=F.fDeptCode
																				WHERE '+@WHERE+' order by R.fRecordedTime'      
 PRINT @SQL        
 EXEC(@SQL )   
end   
GO
--REPORT_EDIT_1 出纳日报表UP_Report_Cns_Total_CashDays

if exists(select * from sysobjects where id = object_id(N'[UP_Report_Cns_Total_CashDays]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
 drop procedure UP_Report_Cns_Total_CashDays
GO
create procedure [dbo].[UP_Report_Cns_Total_CashDays] @STATIONID  varchar(2),    -- 工作站  
      @oper_id  varchar(1024),  --操作员ID  
      @DateTime varchar(20)     --查询日期   
      as  
begin  
declare @sqlstr varchar(8000)  
set @sqlstr =   
'SELECT  b.fOperName as [操作员]  
 --, SUM([消费|次]) as [消费|次], SUM([消费|金额]) as [消费|金额]  
 , SUM([金额充值|次]) as [金额充值|次], SUM([金额充值|金额]) as [金额充值|金额]
 , SUM([次数充值|次]) as [次数充值|次], SUM([次数充值|金额]) as [次数充值|金额]
 , SUM([存款|管理费]) as [存款|管理费]
 , SUM([金额取款|次]) as [金额取款|次], SUM([金额取款|金额]) as [金额取款|金额]
 , SUM([次数取款|次]) as [次数取款|次], SUM([次数取款|金额]) as [次数取款|金额]
 , SUM([金额补助|次]) as [金额补助|次], SUM([金额补助|金额]) as [金额补助|金额]
 , SUM([次数补助|次]) as [次数补助|次], SUM([次数补助|金额]) as [次数补助|金额]
 , SUM([补助清除|次]) as [补助清除|次], SUM([补助清除|金额]) as [补助清除|金额]  
 , SUM([挂失|次]) as [挂失|次], SUM([挂失|金额]) as [挂失|金额], SUM([挂失|手续费]) as [挂失|手续费]  
 , SUM([解挂|次]) as [解挂|次], SUM([解挂|金额]) as [解挂|金额], SUM([解挂|手续费]) as [解挂|手续费]  
 , SUM([开户|次]) as [开户|次], SUM([开户|金额]) as [开户|金额], SUM([开户|卡费]) as [开户|卡费], SUM([开户|押金]) as [开户|押金], SUM([开户|管理费]) as [开户|管理费]  
 , SUM([有卡撤户|次]) as [有卡撤户|次], SUM([有卡撤户|金额]) as [有卡撤户|金额], SUM([有卡撤户|手续费]) as [有卡撤户|手续费], SUM([有卡撤户|押金]) as [有卡撤户|押金]  
 , SUM([纠错|次]) as [纠错|次], SUM([纠错|金额]) as [纠错|金额]  
 , SUM([换卡|次]) as [换卡|次], SUM([换卡|金额]) as [换卡|金额], SUM([换卡|手续费]) as [换卡|手续费]  
 , SUM([补卡|次]) as [补卡|次], SUM([补卡|金额]) as [补卡|金额], SUM([补卡|手续费]) as [补卡|手续费], SUM([补卡|卡费]) as [补卡|卡费]  
 , SUM([有卡变更|次]) as [有卡变更|次], SUM([有卡变更|金额]) as [有卡变更|金额]  
 --, SUM([自动挂失|次]) as [自动挂失|次], SUM([自动挂失|金额]) as [自动挂失|金额]  
 --, SUM([无卡变更|次]) as [无卡变更|次], SUM([无卡变更|金额]) as [无卡变更|金额]  
 , SUM([人工冻结|次]) as [人工冻结|次], SUM([人工冻结|金额]) as [人工冻结|金额]  
 --, SUM([自动冻结|次]) as [自动冻结|次], SUM([自动冻结|金额]) as [自动冻结|金额]  
 , SUM([无卡撤户|次]) as [无卡撤户|次], SUM([无卡撤户|金额]) as [无卡撤户|金额], SUM([无卡撤户|手续费]) as [无卡撤户|手续费], SUM([无卡撤户|押金]) as [无卡撤户|押金]  
 , SUM([补发卡|次]) as [补发卡|次], SUM([补发卡|金额]) as [补发卡|金额]  
 , SUM([解冻|次]) as [解冻|次], SUM([解冻|金额]) as [解冻|金额]  
 --, SUM([圈存|次]) as [圈存|次], SUM([圈存|金额]) as [圈存|金额], SUM([圈存|管理费]) as [圈存|管理费]  
 --, SUM([圈存补款|次]) as [圈存补款|次], SUM([圈存补款|金额]) as [圈存补款|金额]  
 --, SUM([圈提|次]) as [圈提|次], SUM([圈提|金额]) as [圈提|金额]   
 --, SUM([优惠|次]) as [优惠|次], SUM([优惠|金额]) as [优惠|金额]  
 --, SUM([计次|次]) as [计次|次], SUM([计次|金额]) as [计次|金额]  
 --, SUM([转入|次]) as [转入|次], SUM([转入|金额]) as [转入|金额]  
 --, SUM([转出|次]) as [转出|次], SUM([转出|金额]) as [转出|金额]  
 --, SUM([删除资料|次]) as [删除资料|次], SUM([删除资料|金额]) as [删除资料|金额]  
 , SUM([销卡|次]) as [销卡|次], SUM([销卡|金额]) as [销卡|金额]  
 , (SUM([金额充值|次])+SUM([金额取款|次])+SUM([金额补助|次])+SUM([挂失|次])+SUM([解挂|次])+SUM([开户|次])+SUM([有卡撤户|次])+  
    SUM([纠错|次])+SUM([换卡|次])+SUM([补卡|次])+SUM([有卡变更|次])+SUM([自动挂失|次])+SUM([无卡变更|次])+  
    SUM([人工冻结|次])+SUM([自动冻结|次])+SUM([无卡撤户|次])+SUM([补发卡|次])+SUM([解冻|次])+SUM([圈存|次])+  
    SUM([圈存补款|次])+SUM([圈提|次])+SUM([优惠|次])+SUM([计次|次])+SUM([转入|次])+SUM([转出|次])+SUM([删除资料|次])+  
    SUM([销卡|次])) as [发生总人数]  
 , SUM([开户|金额])+SUM([开户|卡费])+SUM([开户|押金])+SUM([开户|管理费])+  
   SUM([有卡撤户|手续费])-SUM([有卡撤户|金额])-SUM([有卡撤户|押金])+  
   SUM([无卡撤户|手续费])-SUM([无卡撤户|金额])-SUM([无卡撤户|押金])+  
   SUM([金额充值|金额])+SUM([存款|管理费])-SUM([金额取款|金额]) as [上缴总金额]  
   FROM V_C_SUM_OPER a left join T_B_Manager B on A.fOperID = b.fOperID ' + char(13) +  
   ' where fDate = ''' + @DateTime + ''' '  
if(@STATIONID <> '')  
  set @sqlstr = + @sqlstr + ' and b.fStationId like (''' + @STATIONID +'%'') '     
if(@oper_id <> '')  
  set @sqlstr = + @sqlstr + 'and ' + @oper_id   
  
set @sqlstr = @sqlstr   + char(13) +  
              'group by a.fOperID,b.fOperName'  
 print @sqlstr  
 exec(@sqlstr)  
end  

GO

--REPORT_EDIT_2 出纳月报表UP_Report_Cns_Total_CashMonth
if exists(select * from sysobjects where id = object_id(N'[UP_Report_Cns_Total_CashMonth]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
 drop procedure UP_Report_Cns_Total_CashMonth
GO

create procedure [dbo].[UP_Report_Cns_Total_CashMonth] @STATIONID varchar(2), -- 工作站
    @oper_id varchar(1024), --操作员ID
    @Year varchar(4), --查询年份；yyyy
    @Month varchar(2) --查询月份；mm
    as
    begin
        declare @sqlstr varchar(8000)
        DECLARE @Begin datetime,
            @end datetime,
            @strB varchar(30),
            @strE varchar(30)
/*        ,@Year varchar(4)  
        ,@Month varchar(2)   
     set  @Year = '2013'     
     set  @Month = '04'*/
        SET @Begin = @Year + '-' + dbo.fn_FillZero(2, @Month) + '-01 00:00:00'
        SET @end = @Year + '-' + dbo.fn_FillZero(2, @Month) + '-' +
                   cast(32 - Day(@Begin + (32 - Day(@Begin))) as varchar(2)) + ' 23:59:59'
        --print @Begin
--print @end  
        SET @strB = CONVERT(varchar(100), @Begin, 20)
        SET @strE = CONVERT(varchar(100), @end, 20)
        --print @strB
--print @strE  
        set @sqlstr =
                    'SELECT  b.fOperName as [操作员]
                     --, SUM([消费|次]) as [消费|次], SUM([消费|金额]) as [消费|金额]
                     , SUM([金额充值|次]) as [金额充值|次], SUM([金额充值|金额]) as [金额充值|金额]
                     , SUM([次数充值|次]) as [次数充值|次], SUM([次数充值|金额]) as [次数充值|金额]
                     , SUM([存款|管理费]) as [存款|管理费]
                     , SUM([金额取款|次]) as [金额取款|次], SUM([金额取款|金额]) as [金额取款|金额]
                     , SUM([次数取款|次]) as [次数取款|次], SUM([次数取款|金额]) as [次数取款|金额]
                     , SUM([金额补助|次]) as [金额补助|次], SUM([金额补助|金额]) as [金额补助|金额]
                     , SUM([次数补助|次]) as [次数补助|次], SUM([次数补助|金额]) as [次数补助|金额]
                     , SUM([补助清除|次]) as [补助清除|次], SUM([补助清除|金额]) as [补助清除|金额]
                     , SUM([挂失|次]) as [挂失|次], SUM([挂失|金额]) as [挂失|金额], SUM([挂失|手续费]) as [挂失|手续费]
                     , SUM([解挂|次]) as [解挂|次], SUM([解挂|金额]) as [解挂|金额], SUM([解挂|手续费]) as [解挂|手续费]
                     , SUM([开户|次]) as [开户|次], SUM([开户|金额]) as [开户|金额], SUM([开户|卡费]) as [开户|卡费], SUM([开户|押金]) as [开户|押金], SUM([开户|管理费]) as [开户|管理费]
                     , SUM([有卡撤户|次]) as [有卡撤户|次], SUM([有卡撤户|金额]) as [有卡撤户|金额], SUM([有卡撤户|手续费]) as [有卡撤户|手续费], SUM([有卡撤户|押金]) as [有卡撤户|押金]
                     , SUM([纠错|次]) as [纠错|次], SUM([纠错|金额]) as [纠错|金额]
                     , SUM([换卡|次]) as [换卡|次], SUM([换卡|金额]) as [换卡|金额], SUM([换卡|手续费]) as [换卡|手续费]
                     , SUM([补卡|次]) as [补卡|次], SUM([补卡|金额]) as [补卡|金额], SUM([补卡|手续费]) as [补卡|手续费], SUM([补卡|卡费]) as [补卡|卡费]
                     , SUM([有卡变更|次]) as [有卡变更|次], SUM([有卡变更|金额]) as [有卡变更|金额]
                     --, SUM([自动挂失|次]) as [自动挂失|次], SUM([自动挂失|金额]) as [自动挂失|金额]
                     --, SUM([无卡变更|次]) as [无卡变更|次], SUM([无卡变更|金额]) as [无卡变更|金额]
                     , SUM([人工冻结|次]) as [人工冻结|次], SUM([人工冻结|金额]) as [人工冻结|金额]
                     --, SUM([自动冻结|次]) as [自动冻结|次], SUM([自动冻结|金额]) as [自动冻结|金额]
                     , SUM([无卡撤户|次]) as [无卡撤户|次], SUM([无卡撤户|金额]) as [无卡撤户|金额], SUM([无卡撤户|手续费]) as [无卡撤户|手续费], SUM([无卡撤户|押金]) as [无卡撤户|押金]
                     , SUM([补发卡|次]) as [补发卡|次], SUM([补发卡|金额]) as [补发卡|金额]
                     , SUM([解冻|次]) as [解冻|次], SUM([解冻|金额]) as [解冻|金额]
                     --, SUM([圈存|次]) as [圈存|次], SUM([圈存|金额]) as [圈存|金额], SUM([圈存|管理费]) as [圈存|管理费]
                     --, SUM([圈存补款|次]) as [圈存补款|次], SUM([圈存补款|金额]) as [圈存补款|金额]
                     --, SUM([圈提|次]) as [圈提|次], SUM([圈提|金额]) as [圈提|金额]
                     --, SUM([优惠|次]) as [优惠|次], SUM([优惠|金额]) as [优惠|金额]
                     --, SUM([计次|次]) as [计次|次], SUM([计次|金额]) as [计次|金额]
                     --, SUM([转入|次]) as [转入|次], SUM([转入|金额]) as [转入|金额]
                     --, SUM([转出|次]) as [转出|次], SUM([转出|金额]) as [转出|金额]
                     --, SUM([删除资料|次]) as [删除资料|次], SUM([删除资料|金额]) as [删除资料|金额]
                     , SUM([销卡|次]) as [销卡|次], SUM([销卡|金额]) as [销卡|金额]
                     , (SUM([金额充值|次])+SUM([金额取款|次])+SUM([金额补助|次])+SUM([挂失|次])+SUM([解挂|次])+SUM([开户|次])+SUM([有卡撤户|次])+
                        SUM([纠错|次])+SUM([换卡|次])+SUM([补卡|次])+SUM([有卡变更|次])+SUM([自动挂失|次])+SUM([无卡变更|次])+
                        SUM([人工冻结|次])+SUM([自动冻结|次])+SUM([无卡撤户|次])+SUM([补发卡|次])+SUM([解冻|次])+SUM([圈存|次])+
                        SUM([圈存补款|次])+SUM([圈提|次])+SUM([优惠|次])+SUM([计次|次])+SUM([转入|次])+SUM([转出|次])+SUM([删除资料|次])+
                        SUM([销卡|次])) as [发生总人数]
                     , SUM([开户|金额])+SUM([开户|卡费])+SUM([开户|押金])+SUM([开户|管理费])+
                       SUM([有卡撤户|手续费])-SUM([有卡撤户|金额])-SUM([有卡撤户|押金])+
                       SUM([无卡撤户|手续费])-SUM([无卡撤户|金额])-SUM([无卡撤户|押金])+
                       SUM([金额充值|金额])+SUM([存款|管理费])-SUM([金额取款|金额]) as [上缴总金额]
                       FROM V_C_SUM_OPER a left join T_B_Manager B on A.fOperID = b.fOperID ' + char(13) +
                    ' where fDate >= ''' + @strB + ''' and fDate <= ''' + @strE + ''' '
        if (@STATIONID <> '')
            set @sqlstr = + @sqlstr + ' and b.fStationId like (''' + @STATIONID + '%'') '

        if (@oper_id <> '')
            set @sqlstr = + @sqlstr + ' and ' + @oper_id

        set @sqlstr = @sqlstr + char(13) +
                      'group by a.fOperID,b.fOperName'
        --print @sqlstr
        exec (@sqlstr)
    end

GO


--REPORT_EDIT_3 出纳阶段报表UP_Report_Cns_Total_CashStaged

if exists(select * from sysobjects where id = object_id(N'[UP_Report_Cns_Total_CashStaged]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
 drop procedure UP_Report_Cns_Total_CashStaged
GO
create procedure [dbo].[UP_Report_Cns_Total_CashStaged] @STATIONID  varchar(2),     -- 工作站  
      @oper_id  varchar(1024),   --操作员ID  
      @BegDateTime varchar(20),     --查询开始日期；yyyy-mm-dd  
      @EndDateTime varchar(20)     --查询结束日期；yyyy-mm-dd   
      as  
begin  
declare @SQLSTR varchar(8000)  
DECLARE @strB varchar(30),  
  @strE varchar(30)  
SET @strB = CONVERT(varchar(20), @BegDateTime, 23) + ' 00:00:00'  
SET @strE = CONVERT(varchar(20), @EndDateTime, 23) + ' 23:59:59'  
--print @strB  
--print @strE  
set @sqlstr =   
'SELECT  b.fOperName as [操作员]  
 --, SUM([消费|次]) as [消费|次], SUM([消费|金额]) as [消费|金额]  
 , SUM([金额充值|次]) as [金额充值|次], SUM([金额充值|金额]) as [金额充值|金额]
 , SUM([次数充值|次]) as [次数充值|次], SUM([次数充值|金额]) as [次数充值|金额]
 , SUM([存款|管理费]) as [存款|管理费]
 , SUM([金额取款|次]) as [金额取款|次], SUM([金额取款|金额]) as [金额取款|金额]
 , SUM([次数取款|次]) as [次数取款|次], SUM([次数取款|金额]) as [次数取款|金额]
 , SUM([金额补助|次]) as [金额补助|次], SUM([金额补助|金额]) as [金额补助|金额]
 , SUM([次数补助|次]) as [次数补助|次], SUM([次数补助|金额]) as [次数补助|金额]
 , SUM([补助清除|次]) as [补助清除|次], SUM([补助清除|金额]) as [补助清除|金额]  
 , SUM([挂失|次]) as [挂失|次], SUM([挂失|金额]) as [挂失|金额], SUM([挂失|手续费]) as [挂失|手续费]  
 , SUM([解挂|次]) as [解挂|次], SUM([解挂|金额]) as [解挂|金额], SUM([解挂|手续费]) as [解挂|手续费]  
 , SUM([开户|次]) as [开户|次], SUM([开户|金额]) as [开户|金额], SUM([开户|卡费]) as [开户|卡费], SUM([开户|押金]) as [开户|押金], SUM([开户|管理费]) as [开户|管理费]  
 , SUM([有卡撤户|次]) as [有卡撤户|次], SUM([有卡撤户|金额]) as [有卡撤户|金额], SUM([有卡撤户|手续费]) as [有卡撤户|手续费], SUM([有卡撤户|押金]) as [有卡撤户|押金]  
 , SUM([纠错|次]) as [纠错|次], SUM([纠错|金额]) as [纠错|金额]  
 , SUM([换卡|次]) as [换卡|次], SUM([换卡|金额]) as [换卡|金额], SUM([换卡|手续费]) as [换卡|手续费]  
 , SUM([补卡|次]) as [补卡|次], SUM([补卡|金额]) as [补卡|金额], SUM([补卡|手续费]) as [补卡|手续费], SUM([补卡|卡费]) as [补卡|卡费]  
 , SUM([有卡变更|次]) as [有卡变更|次], SUM([有卡变更|金额]) as [有卡变更|金额]  
 --, SUM([自动挂失|次]) as [自动挂失|次], SUM([自动挂失|金额]) as [自动挂失|金额]  
 --, SUM([无卡变更|次]) as [无卡变更|次], SUM([无卡变更|金额]) as [无卡变更|金额]  
 , SUM([人工冻结|次]) as [人工冻结|次], SUM([人工冻结|金额]) as [人工冻结|金额]  
 --, SUM([自动冻结|次]) as [自动冻结|次], SUM([自动冻结|金额]) as [自动冻结|金额]  
 , SUM([无卡撤户|次]) as [无卡撤户|次], SUM([无卡撤户|金额]) as [无卡撤户|金额], SUM([无卡撤户|手续费]) as [无卡撤户|手续费], SUM([无卡撤户|押金]) as [无卡撤户|押金]  
 , SUM([补发卡|次]) as [补发卡|次], SUM([补发卡|金额]) as [补发卡|金额]  
 , SUM([解冻|次]) as [解冻|次], SUM([解冻|金额]) as [解冻|金额]  
 --, SUM([圈存|次]) as [圈存|次], SUM([圈存|金额]) as [圈存|金额], SUM([圈存|管理费]) as [圈存|管理费]  
 --, SUM([圈存补款|次]) as [圈存补款|次], SUM([圈存补款|金额]) as [圈存补款|金额]  
 --, SUM([圈提|次]) as [圈提|次], SUM([圈提|金额]) as [圈提|金额]   
 --, SUM([优惠|次]) as [优惠|次], SUM([优惠|金额]) as [优惠|金额]  
 --, SUM([计次|次]) as [计次|次], SUM([计次|金额]) as [计次|金额]  
 --, SUM([转入|次]) as [转入|次], SUM([转入|金额]) as [转入|金额]  
 --, SUM([转出|次]) as [转出|次], SUM([转出|金额]) as [转出|金额]  
 --, SUM([删除资料|次]) as [删除资料|次], SUM([删除资料|金额]) as [删除资料|金额]  
 , SUM([销卡|次]) as [销卡|次], SUM([销卡|金额]) as [销卡|金额]  
 , (SUM([金额充值|次])+SUM([金额取款|次])+SUM([金额补助|次])+SUM([挂失|次])+SUM([解挂|次])+SUM([开户|次])+SUM([有卡撤户|次])+  
    SUM([纠错|次])+SUM([换卡|次])+SUM([补卡|次])+SUM([有卡变更|次])+SUM([自动挂失|次])+SUM([无卡变更|次])+  
    SUM([人工冻结|次])+SUM([自动冻结|次])+SUM([无卡撤户|次])+SUM([补发卡|次])+SUM([解冻|次])+SUM([圈存|次])+  
    SUM([圈存补款|次])+SUM([圈提|次])+SUM([优惠|次])+SUM([计次|次])+SUM([转入|次])+SUM([转出|次])+SUM([删除资料|次])+  
    SUM([销卡|次])) as [发生总人数]  
 , SUM([开户|金额])+SUM([开户|卡费])+SUM([开户|押金])+SUM([开户|管理费])+  
   SUM([有卡撤户|手续费])-SUM([有卡撤户|金额])-SUM([有卡撤户|押金])+  
   SUM([无卡撤户|手续费])-SUM([无卡撤户|金额])-SUM([无卡撤户|押金])+  
   SUM([金额充值|金额])+SUM([存款|管理费])-SUM([金额取款|金额]) as [上缴总金额]  
   FROM V_C_SUM_OPER a left join T_B_Manager B on A.fOperID = b.fOperID ' + char(13) +  
   ' where fDate >= ''' + @strB + ''' and fDate <= ''' + @strE + ''' '  
if(@STATIONID <> '')  
  set @sqlstr = + @sqlstr + ' and b.fStationId like (''' + @STATIONID +'%'') '  
if(@oper_id <> '')  
  set @sqlstr = + @sqlstr + ' and ' + @oper_id   
  
set @sqlstr = @sqlstr + char(13) +  
              'group by a.fOperID,b.fOperName'  
 --print @sqlstr  
 exec(@sqlstr)  
end  
GO

--REPORT_EDIT_4 营业日报表UP_Report_Cns_ConsDay

if exists(select  * from sys.all_objects where name='UP_Report_Cns_ConsDay' and type='P')
drop procedure UP_Report_Cns_ConsDay
GO
CREATE procedure [dbo].[UP_Report_Cns_ConsDay] @STATIONID VARCHAR(2),  --工作站                
   @CONSDAY VARCHAR(10),   --日期           
   @St_Name varchar(4000),  
   @fBz_id varchar(4000)  
    as          
BEGIN          
DECLARE @SQLSTR varchar(8000),          
  @strB varchar(30),          
  @strE varchar(30),          
  @StrSTA varchar(4000)          
 SET @strB = CONVERT(varchar(20), @CONSDAY, 23) + ' 00:00:00'          
 SET @strE = CONVERT(varchar(20), @CONSDAY, 23) + ' 23:59:59'           
          
 IF (@STATIONID<>'')          
  SET @StrSTA = ' AND A.FSTATION_ID=''' + @STATIONID + ''''          
 else          
  SET @StrSTA = ''   
  
IF (@St_Name<>'')          
  SET @StrSTA = @StrSTA+' AND ' + @St_Name       
IF (@fBz_id<>'')          
  SET @StrSTA = @StrSTA+' AND ' + @fBz_id                  
          
 SET @SQLSTR =           
  'SELECT A.FSTATION_NAME AS 工作站名称, A.FST_NAME AS 营业组, A.FBZ_NAME AS 班组,           
   A.FPOSNAME AS 消费机,           
   B.fPurseName 钱包类型,    
   CAST(SUM(R.[消费|金额]) AS NUMERIC(9, 2)) AS 消费金额,           
   CAST(SUM(R.[消费|次]) AS INT) AS 消费次数,           
   CAST(SUM(R.[纠错|金额]) AS NUMERIC(9, 2)) AS 纠错金额,           
   CAST(SUM(R.[纠错|次]) AS INT) AS 纠错次数,          
   --CAST(SUM(R.[计次|次]) AS INT) AS 计次次数,             
   CAST(SUM(R.[消费|金额] - R.[纠错|金额]) AS NUMERIC(18, 2)) - CAST(SUM(ROUND((A.FTC_BL / 100)           
     * (R.[消费|金额] - R.[纠错|金额]), 2)) AS NUMERIC(18, 2)) AS 实际金额          
  FROM V_C_SUM_Pos R Left JOIN          
    V_B_SITEPOS A ON R.fPosID=A.fPosId   Left JOIN      
    T_B_PurseCode B ON R.fPurseID = B.fPurseCode        
  WHERE A.FPOSTYPE IN (1,4) AND R.fDate>='''+@strB+''' AND R.fDate<='''+@strE+''' ' + CHAR(13) +          
  @StrSTA + CHAR(13) +          
  'GROUP BY A.FSTATION_NAME, A.FST_ID,A.FBZ_ID, A.FPOSID,B.fPurseName, A.FST_NAME, A.FBZ_NAME, A.FPOSNAME          
  ORDER BY A.FSTATION_NAME, A.FST_ID,A.FBZ_ID, A.FPOSID '          
 print @sqlstr          
 exec(@sqlstr)          
END      
GO

--REPORT_EDIT_5 营业月报表UP_Report_Cns_ConsMonth

if exists(select  * from sys.all_objects where name='UP_Report_Cns_ConsMonth' and type='P')
drop procedure UP_Report_Cns_ConsMonth
GO
CREATE procedure [dbo].[UP_Report_Cns_ConsMonth] @STATIONID varchar(2), --工作站        
   @Year varchar(4),       --年        
   @Month varchar(2),       --月         
   @St_Name varchar(4000),  
   @fBz_id varchar(4000)  
    as        
BEGIN        
 DECLARE @SQLSTR varchar(8000),        
   @Begin datetime,        
   @end   datetime,        
   @strB varchar(30),        
   @strE varchar(30),        
   @StrSTA varchar(4000)        
 SET @Begin = @Year + '-' + dbo.fn_FillZero(2,@Month) + '-01 00:00:00'        
 SET @end = @Year + '-' + dbo.fn_FillZero(2,@Month) + '-' + cast(32-Day(@Begin+(32-Day(@Begin))) as varchar(2)) + ' 23:59:59'        
 SET @strB = CONVERT(varchar(100), @Begin, 20)        
 SET @strE = CONVERT(varchar(100), @end, 20)        
 IF (@STATIONID<>'')        
  SET @StrSTA = ' AND A.FSTATION_ID=''' + @STATIONID + ''''        
 else        
  SET @StrSTA = ''     
    
  IF (@St_Name<>'')          
  SET @StrSTA = @StrSTA+' AND ' + @St_Name       
IF (@fBz_id<>'')          
  SET @StrSTA = @StrSTA+' AND ' + @fBz_id       
        
 SET @SQLSTR =         
  'SELECT A.FSTATION_NAME AS 工作站名称, A.FST_NAME AS 营业组, A.FBZ_NAME AS 班组,         
   A.FPOSNAME AS 消费机,     
   B.fPurseName 钱包类型,        
   CAST(SUM(R.[消费|金额]) AS NUMERIC(9, 2)) AS 消费金额,         
   CAST(SUM(R.[消费|次]) AS INT) AS 消费次数,         
   CAST(SUM(R.[纠错|金额]) AS NUMERIC(9, 2)) AS 纠错金额,         
   CAST(SUM(R.[纠错|次]) AS INT) AS 纠错次数,         
   --CAST(SUM(R.[计次|次]) AS INT) AS 计次次数,         
   CAST(SUM(R.[消费|金额] - R.[纠错|金额]) AS NUMERIC(18, 2)) - CAST(SUM(ROUND((A.FTC_BL / 100)         
     * (R.[消费|金额] - R.[纠错|金额]), 2)) AS NUMERIC(18, 2)) AS 实际金额        
  FROM V_C_SUM_Pos R Left JOIN        
    V_B_SITEPOS A ON R.fPosID=A.fPosId  Left JOIN      
    T_B_PurseCode B ON R.fPurseID = B.fPurseCode      
  WHERE A.FPOSTYPE IN (1,4) AND R.fDate>='''+@strB+''' AND R.fDate<='''+@strE+''' ' + CHAR(13) +        
  @StrSTA + CHAR(13) +        
  'GROUP BY A.FSTATION_NAME, A.FST_ID,A.FBZ_ID, A.FPOSID,B.fPurseName, A.FST_NAME, A.FBZ_NAME, A.FPOSNAME        
  ORDER BY A.FSTATION_NAME, A.FST_ID,A.FBZ_ID, A.FPOSID '        
  print @sqlstr        
  exec(@sqlstr)        
END      
GO

--REPORT_EDIT_6 营业阶段报表UP_Report_Cns_ConsSpace

if exists(select  * from sys.all_objects where name='UP_Report_Cns_ConsSpace' and type='P')
drop procedure UP_Report_Cns_ConsSpace
GO
CREATE procedure [dbo].[UP_Report_Cns_ConsSpace] @STATIONID varchar(2),        
   @BeginDate datetime,        
   @EndDate datetime,  
   @St_Name varchar(4000),  
   @fBz_id varchar(4000)         
    as        
BEGIN        
 DECLARE @SQLSTR varchar(8000),        
   @strB varchar(30),        
   @strE varchar(30),        
   @StrSTA varchar(4000)        
 SET @strB = CONVERT(varchar(20), @BeginDate, 23) + ' 00:00:00'        
 SET @strE = CONVERT(varchar(20), @EndDate, 23) + ' 23:59:59'        
 IF (@STATIONID<>'')        
  SET @StrSTA = ' AND A.FSTATION_ID=''' + @STATIONID + ''''        
 else        
  SET @StrSTA = ''   
    
 IF (@St_Name<>'')          
   SET @StrSTA = @StrSTA+' AND ' + @St_Name       
 IF (@fBz_id<>'')          
   SET @StrSTA = @StrSTA+' AND ' + @fBz_id       
          
 SET @SQLSTR =         
  'SELECT A.FSTATION_NAME AS 工作站名称, A.FST_NAME AS 营业组, A.FBZ_NAME AS 班组,         
   A.FPOSNAME AS 消费机,      
   B.fPurseName 钱包类型,          
   CAST(SUM(R.[消费|金额]) AS NUMERIC(9, 2)) AS 消费金额,         
   CAST(SUM(R.[消费|次]) AS INT) AS 消费次数,         
   CAST(SUM(R.[纠错|金额]) AS NUMERIC(9, 2)) AS 纠错金额,         
   CAST(SUM(R.[纠错|次]) AS INT) AS 纠错次数,         
  -- CAST(SUM(R.[计次|次]) AS INT) AS 计次次数,         
   CAST(SUM(R.[消费|金额] - R.[纠错|金额]) AS NUMERIC(18, 2)) - CAST(SUM(ROUND((A.FTC_BL / 100)         
     * (R.[消费|金额] - R.[纠错|金额]), 2)) AS NUMERIC(18, 2)) AS 实际金额        
  FROM V_C_SUM_Pos R Left JOIN        
   V_B_SITEPOS A ON R.fPosID=A.fPosId  Left JOIN      
    T_B_PurseCode B ON R.fPurseID = B.fPurseCode        
  WHERE A.FPOSTYPE IN (1,4) AND R.fDate>='''+@strB+''' AND R.fDate<='''+@strE+''' ' + CHAR(13) +        
  @StrSTA + CHAR(13) +        
  'GROUP BY A.FSTATION_NAME, A.FST_ID,A.FBZ_ID, A.FPOSID,B.fPurseName, A.FST_NAME, A.FBZ_NAME, A.FPOSNAME        
  ORDER BY A.FSTATION_NAME, A.FST_ID,A.FBZ_ID, A.FPOSID '        
  --print @sqlstr        
  exec(@sqlstr)        
END      
go

--REPORT_EDIT_7 流水记录报表增加钱包名称字段显示
if exists(select * from sysobjects where id = object_id(N'[UP_Report_Cns_RecordN]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
 drop procedure UP_Report_Cns_RecordN
GO
CREATE procedure [dbo].[UP_Report_Cns_RecordN]     
    @STATIONID VARCHAR(2),  --工作站          
  @strWhere varchar(1000),    
  @RecType varchar(2),    
  @BeginDate VARCHAR(20),         
  @BeginTime VARCHAR(20),    
  @EndDate VARCHAR(20),    
  @EndTime VARCHAR(20),    
  @PosID varchar(5)='',    
    @Page int = 1,              --查询页面    
    @Ret varchar(80) output --返回值  X|Y|Z 格式 X:1查询时段不正确  2查询的流水表不存在  0成功; Y:在总记录数  Z:总的页数      
as    
BEGIN    
 DECLARE @strB varchar(30),    
         @strE varchar(30)    
 SET @strB = CONVERT(varchar(20), @BeginDate, 23) + ' ' + CONVERT(varchar(20), @BeginTime, 24)    
 SET @strE = CONVERT(varchar(20), @EndDate, 23)   + ' ' + CONVERT(varchar(20), @EndTime, 24)    
/*    
 SET @strB = datename(yyyy, @BeginDate)+'-'+datename(mm, @BeginDate)+'-'+datename(dd, @BeginDate)+' '+datename(hh, @BeginTime)+':'+datename(mi, @BeginTime)+':'+datename(ss, @BeginTime)    
 SET @strE = datename(yyyy, @EndDate)  +'-'+datename(mm, @EndDate)  +'-'+datename(dd, @EndDate)  +' '+datename(hh, @EndTime)  +':'+datename(mi, @EndTime)  +':'+datename(ss, @EndTime)    
*/    
 DECLARE @STRSQL nvarchar(4000),    
         @Where nvarchar(1000),    
         @EmpSel varchar(300),    
         @iRet int,    
         @sRet varchar(300)    
             
 set @Ret = '0|0|0'    
 EXEC UP_R_CheckTime @BeginDate, @EndDate, 1, @iRet output, @sRet output    
 if @iRet = -9999 OR @sRet = ''    
 begin    
  set @Ret = '0|0|0'    
  if @iRet = -9999    
    SET @STRSQL = 'SELECT ''查询表无效-查询表范围超期'' AS [返回信息]'    
     else if @sRet = ''    
       SET @STRSQL = 'SELECT ''查询表无效-查询范围内没有流水产生'' AS [返回信息]'    
     else    
       SET @STRSQL = 'SELECT ''查询表无效-无法确定的原因'' AS [返回信息]'      
  --print @STRSQL       
  exec(@STRSQL)    
  Return    
 end     
    
 IF (@strWhere<>'')    
      SET @Where =  ' fAccountid in (select fAccountID  from T_B_Employee where ' +  @strWhere + ') '    
    ELSE    
   SET @Where = ' fAccountid<>''00000000'' '    
    Set @Where = @Where + ' and fSettleTime >= ''' + @strB + ''' and fSettleTime <= ''' + @strE + ''''      
 --IF (@STATIONID<>'')    
 --  SET @Where = @Where + ' and fStation_Id = '''+@STATIONID + ''' '    
 IF (@PosID<>0)    
      SET @Where = @Where + ' and fPosid=' + @PosID + ' '    
    
    IF (@RecType<>'99')    
   SET @Where = @Where + ' and fRecType='+@RecType+' '     
    
 DECLARE @return_value int,    
    @SQLOUT nvarchar(2000),    
    @pageCount int ,    
    @Counts int           
    
  EXEC @return_value = [dbo].[proc_paged_2part_selectMax]    
    @tblName = @sRet ,    
    @fldName = N' fKeyID,fAccountid,fSerialNo,fPurseID,fRecType,fPosid,fCreateTime,fRecvTime,fOldBalance,fAmount,  fNewBalance,  
    fFee1,fFee2,fFee3, fFee4,fDiscount,fSourceID,fPurseTranNo,fCardTranNo, fPosTranNo,fPosOffTranNo,fSiteID,  fDeptCode,fOperID,fMealID  ',    
    @pageSize = 3000,    
    @page = @Page,    
    @fldSort = N'fKeyID',    
    @Sort = 1,    
    @strCondition = @Where ,    
    @ID = N'fKeyID',    
    @Dist = 0,    
    @pageCount = @pageCount OUTPUT,    
    @Counts = @Counts OUTPUT,    
    @SQLOUT = @SQLOUT OUTPUT    
   set @Ret = '0|' + CAST(@Counts as varchar(30)) + '|' + CAST(@pageCount as varchar(30))      
    
  set @STRSQL=    
  '  CREATE TABLE #tmpRec (    
 fKeyID bigint NULL,    
 fAccountid varchar(18) NULL,     
 fSerialNo varchar(30) NULL,    
 fPurseID int NULL,    
 fRecType varchar(2) NULL,    
 fPosid varchar(5) NULL,    
 fCreateTime datetime NULL,   
 fRecvTime DATETIME NULL,   
 fOldBalance numeric(9, 2) NULL,    
 fAmount numeric(9, 2) NULL,    
 fNewBalance numeric(9, 2) NULL,    
 fFee1 numeric(9, 2) NULL,   
 fFee2 numeric(9, 2) NULL,    
 fFee3 numeric(9, 2) NULL,    
 fFee4 numeric(9, 2) NULL,     
 fDiscount numeric(9, 2) NULL,    
 fSourceID INT,  
 fPurseTranNo int NULL,    
 fCardTranNo INT NULL,   
 fPosTranNo INT,      
 fPosOffTranNo INT,  
 fSiteID varchar(2) NULL,    
 fDeptCode varchar(18) NULL,    
 fOperID varchar(20) NULL,    
 fMealID varchar(3) NULL   
 ) ON [PRIMARY] ' + CHAR(13)+    
 ' insert into #tmpRec ' + @SQLOUT  + CHAR(13)+    
  ' SELECT R.fKeyID AS 序号,E.fName AS 姓名,R.fAccountid AS 账号,R.fSerialNo AS 卡号,    
 D.fDeptName AS 部门,E.fEmployeeCode AS 工号,R.fPosid AS 机号,P.fPosName AS 机器名,    
 M.fMeal_Name AS 交易班次,PU.fPurseName 钱包名称,C.fStateName AS 交易类型,R.fCreateTime AS 交易时间,R.fRecvTime AS 收取时间,    
 R.fOldBalance AS 原余额,R.fAmount AS 交易额,R.fNewBalance AS 现余额,  
   
 R.fFee1 手续费,  
R.fFee2 卡费,  
R.fFee3 押金,  
R.fFee4  管理费,  
 S.fStation_Name AS 工作站,    
 B.fOperName AS 操作员,R.fRecType AS 交易编码    
  FROM #tmpRec R LEFT JOIN     
  T_B_Pos P ON P.fPosid = R.fPosid LEFT JOIN    
  T_B_Station S ON S.fStation_Id = SUBSTRING(P.fSiteID, 1, 2) LEFT JOIN    
  T_B_Employee E ON R.fAccountid = E.fAccountID LEFT JOIN    
  T_B_Dept D ON R.fDeptCode = D.fDeptCode LEFT JOIN    
  T_B_Manager B ON R.fOperid = B.fOperID LEFT JOIN    
  T_B_MealSet M ON R.fMealid = M.fMeal_Id LEFT JOIN    
  T_C_ConsState C ON R.fRecType = C.fStateID  LEFT JOIN      
  T_B_PurseCode PU ON R.fPurseID=PU.fPurseCode 
  order by R.fKeyID  desc  
  drop table #tmpRec '    
  print @strsql    
  exec sp_executesql @strsql    
END  
GO
if exists(select * from sysobjects where id = object_id(N'[UP_Report_Cns_Record]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
 drop procedure UP_Report_Cns_Record
GO
CREATE procedure [dbo].[UP_Report_Cns_Record] @strWhere varchar(1000),
  	@ConsState varchar(2),
  	@BeginDate datetime,
  	@BeginTime datetime,
  	@EndDate datetime,
  	@EndTime datetime,
  	@PosID varchar(5)=''
    as
BEGIN
	DECLARE @strB varchar(30),
	        @strE varchar(30)
	SET @strB = CONVERT(varchar(20), @BeginDate, 23) + ' ' + CONVERT(varchar(20), @BeginTime, 24)
	SET @strE = CONVERT(varchar(20), @EndDate, 23)   + ' ' + CONVERT(varchar(20), @EndTime, 24)
/*
	SET @strB = datename(yyyy, @BeginDate)+'-'+datename(mm, @BeginDate)+'-'+datename(dd, @BeginDate)+' '+datename(hh, @BeginTime)+':'+datename(mi, @BeginTime)+':'+datename(ss, @BeginTime)
	SET @strE = datename(yyyy, @EndDate)  +'-'+datename(mm, @EndDate)  +'-'+datename(dd, @EndDate)  +' '+datename(hh, @EndTime)  +':'+datename(mi, @EndTime)  +':'+datename(ss, @EndTime)
*/
	DECLARE @STRSQL nvarchar(4000),
	        @Where nvarchar(1000),
	        @iRet int,
	        @sRet varchar(300)
	        
	EXEC UP_R_CheckTime @BeginDate, @EndDate, 1, @iRet output, @sRet output
	if @sRet = '' or @iRet = -9999
	begin
      SELECT '查询表无效-查询表范围超期' AS [返回信息] 
	  Return --如果表不存在，直接退出
	end
	declare @VirtualAccountID varchar(40)
	set @VirtualAccountID='00000000'
	SET @Where = ' fAccountid<>''' + @VirtualAccountID + ''' '
    Set @Where = @Where + ' and fSettleTime >= ''' + @strB + ''' and fSettleTime <= ''' + @strE + ''''  
	IF (@PosID<>0)
      SET @Where = @Where + ' and fPosid=' + @PosID + ' '
	IF (@strWhere<>'')
      SET @Where = @strWhere + ' and ' + @Where
    IF (@ConsState<>'99')
	  SET @Where = @Where + ' and fRecType='+@ConsState+' ' 

	DECLARE	@return_value int,
				@SQLOUT nvarchar(2000),
				@pageCount int ,
				@Counts int    			

		EXEC	@return_value = [dbo].[proc_paged_2part_selectMax]
				@tblName = @sRet ,
				@fldName = N' fKeyID,fAccountid,fSerialNo,fPurseTranNo,fPurseID,fRecType,fCreateTime,fOldBalance,fAmount,fNewBalance,fFee1,fFee2,fFee3,fFee4,fPosid,fPosTranNo,fSiteID,fDeptCode,fRecvTime,fSettleTime,fOperid,fMealid ',
				@pageSize = 5000,
				@page = 1,
				@fldSort = N'fKeyID',
				@Sort = 1,
				@strCondition = @Where ,
				@ID = N'fKeyID',
				@Dist = 0,
				@pageCount = @pageCount OUTPUT,
				@Counts = @Counts OUTPUT,
				@SQLOUT = @SQLOUT OUTPUT
  set @STRSQL=
  ' CREATE TABLE #tmpRec (
	fKeyID bigint NULL,
	fAccountid varchar(18) NULL, 
	fSerialNo varchar(30) NULL,
	fPurseTranNo int NULL,
	fPurseID int NULL,
	fRecType varchar(2) NULL,
	fCreateTime datetime NULL,
	fOldBalance numeric(9, 2) NULL,
	fAmount numeric(9, 2) NULL,
	fNewBalance numeric(9, 2) NULL,
	fFee1 numeric(9, 2) NULL,
	fFee2 numeric(9, 2) NULL,
	fFee3 numeric(9, 2) NULL,
	fFee4 numeric(9, 2) NULL,
	fPosid varchar(5) NULL,
	fPosTranNo int NULL,					
	fSiteID varchar(2) NULL,
	fDeptCode varchar(18) NULL,
	fRecvTime datetime NULL,
	fSettleTime datetime NULL,
	fOperid varchar(20) NULL,
	fMealid varchar(3) NULL,
	) ON [PRIMARY] ' + CHAR(13)+
	' insert into #tmpRec ' + @SQLOUT  + CHAR(13)+
  ' SELECT R.fKeyID AS 序号,E.fName AS 姓名,R.fAccountid AS 账号,R.fSerialNo AS 卡号,PC.fPurseName AS 交易钱包,
	D.fDeptName AS 部门,E.fEmployeeCode AS 工号,R.fPosid AS 机号,P.fPosName AS 机器名,
	M.fMeal_Name AS 交易班次,C.fStateName AS 交易类型,R.fCreateTime AS 交易时间,R.fRecvTime AS 收取时间,
	R.fOldBalance AS 原余额,R.fAmount AS 交易额,R.fNewBalance AS 现余额,R.fFee1 AS 手续费,R.fFee2 AS 卡费,
	R.fFee3 AS 押金,R.fFee4 AS 管理费,S.fStation_Name AS 工作站,
	B.fOperName AS 操作员,R.fRecType AS 交易编码, R.fPurseTranNo AS 钱包交易序号, R.fPurseID As 交易钱包号
  FROM #tmpRec R LEFT JOIN 
  T_B_Pos P ON P.fPosID = R.fPosid LEFT JOIN
  T_B_PurseCode PC ON PC.fPurseCode = R.fPurseID LEFT JOIN
  T_B_Station S ON S.fStation_Id = SUBSTRING(P.fSiteID, 1, 2) LEFT JOIN
  T_B_Employee E ON R.fAccountid = E.fAccountID LEFT JOIN
  T_B_Dept D ON R.fDeptCode = D.fDeptCode LEFT JOIN
  T_B_Manager B ON R.fOperid = B.fOperID LEFT JOIN
  T_B_MealSet M ON R.fMealid = M.fMeal_Id LEFT JOIN
  T_C_ConsState C ON R.fRecType = C.fStateID
  order by R.fKeyID  desc  
  drop table #tmpRec '
  print @strsql
  exec sp_executesql @strsql
END
GO

--REPORT_EDIT_8 修改补助领取报表UP_Report_sub_detail_AlreadySubsidy

if exists(select * from dbo.sysobjects where name='UP_Report_sub_detail_AlreadySubsidy' and xtype='P')
   drop procedure [dbo].[UP_Report_sub_detail_AlreadySubsidy]
go    
CREATE procedure [dbo].[UP_Report_sub_detail_AlreadySubsidy]     
      @Station     varchar(20),  -- 工作站；传值，工作站名称，只能传入一个工作站名称    
      @EmpStr      varchar(4000),         
      @BegDateTime varchar(20),  --开始查询日期        
      @EndDateTime varchar(20)  --结束查询日        
     -- @DeptCode   varchar(20),    -- 部门编号,为空查询所有部门          
      as        
BEGIN        
 declare @strB varchar(30),        
   @strE varchar(30),      
   @sql varchar(4000),      
   @where varchar(4000)      
         
   if @EmpStr <>''        
   set @where=' and  a.fAccountID in ( SELECT fAccountID FROM T_B_EMPLOYEE WHERE '+@EmpStr +')'
   else      
   set @where=''      
 SET @strB = CONVERT(varchar(20), @BegDateTime, 23) + ' 00:00:00'        
 SET @strE = CONVERT(varchar(20), @EndDateTime, 23) + ' 23:59:59'         
set @sql='select b.fName as [姓名],         
   b.fEmployeeCode as [学号],         
   c.fDeptName as [部门名称],        
   a.fAccountID as [帐号],  
   fSubMoney    as [发生金额],       
   a.fSubTime as [发放时间],  
   case when a.fClearSub =0 then ''补助领取'' else ''补助清除'' end  as [补助类型],           
   d.fOperName as [操作员]        
 from T_C_Subsidizes a Left join T_B_Employee b on a.fAccountID = b.fAccountID        
        Left join T_B_Dept c on b.fDept = c.fDeptCode        
        Left join T_B_Manager d on d.fOperID = a.fOperID     
   
 where         
   convert(varchar(19),fSubTime,120) >= '''+@strB+''' and convert(varchar(19),fSubTime,120) <='''+ @strE +      
   ''' '+@where+' order by  b.fName'      
 print @sql      
 exec(@sql)       
END    
GO

--REPORT_EDIT_9 修改账户查询报表UP_Report_Cns_Account

if exists(select * from sysobjects where id = object_id(N'[UP_Report_Cns_Account]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
 drop procedure UP_Report_Cns_Account
GO
CREATE procedure [dbo].[UP_Report_Cns_Account]       
      @Station     varchar(20),  -- 工作站；传值，工作站名称，只能传入一个工作站名称      
      @Where       varchar(500)  --查询条件       
      as      
BEGIN     
    print @Where   
    declare @PurseCode int   
    declare @PurseName varchar(50)      
    declare @iCount int     
    declare @sql varchar(4000)     
    declare @ColumnStr varchar(2000)    
    declare @SumStr varchar(2000)    
    declare @Create varchar(2000)   
    declare @Wherestr varchar(2000)      
    set @SumStr=''    
    set @ColumnStr=''    
    set @Create=''    
    set @iCount=0    
    set @Wherestr=''  
    
  if @Where <>''  
  set @Wherestr=' where '+@Where  
    
  declare  Cur_PurseCode cursor for      
  select  fPurseCode,fpurseName from t_b_PurseCode where  fstate=1      
  open Cur_PurseCode      
  fetch next  from Cur_PurseCode into @PurseCode,@PurseName     
  while @@fetch_status = 0      
  begin     
     set @iCount=@iCount+1    
     set @Create=@Create+' alter table #Purse add ['+@PurseName+'] money '    
     if @iCount=1  
        SET @SumStr=@SumStr+'['+@PurseName+']'  
     else  
        SET @SumStr=@SumStr+',['+@PurseName+']'  
          
        set @ColumnStr=@ColumnStr+',isnull(b.['+@PurseName+'],0) ['+@PurseName+'] '   
         
    fetch next from Cur_PurseCode into @PurseCode,@PurseName    
  end      
  close Cur_PurseCode      
  deallocate  Cur_PurseCode     
   
  set @sql='create table #Purse ([账号] varchar(10))'+@Create+'    
            
          insert into #Purse select * from (select  a.fAccountID ,b.fpurseName ,a.fBalance from T_B_Purses a  left join T_B_PurseCode b on  a.fPurseCode=b.fPurseCode) a     
          pivot(max(fbalance) for fpurseName in ('+@SumStr+'))  b  
         select  fName as [姓名] ,a.fAccountID as [账号] ,a.fSerialNo as [卡号] ,a.fDeptName as [部门]      
       ,a.fId_TypeName as [身份类型]       
       ,CASE a.fSex  when 0 then ''女'' when 1 then ''男'' else ''未知'' end as 性别        
       ,CASE a.fCard_State  when 0 then ''正常'' when 1 then ''挂失''  when 2 then ''销卡''   when 3 then ''未发卡'' when 4 then ''撤户''      
                            when 5 then ''开卡失败''   when 6 then ''冻结''   else  ''未知''   end as 状态 '+@ColumnStr+'   
      from v_b_employee a left join #Purse b on a.fAccountID=b.[账号]  '+@Wherestr+' '   
print @sql    
exec(@sql)                    
     
END  
GO

--REPORT_EDIT_10修改账户结余汇总表 UP_Report_SysAccount

IF EXISTS(select  * from sys.all_objects where name='UP_Report_SysAccount' and type='P')
DROP PROCEDURE UP_Report_SysAccount
GO
CREATE PROCEDURE [dbo].[UP_Report_SysAccount]            
  @STATIONID varchar(2),            
  @BeginDate varchar(10),            
  @EndDate   varchar(10)            
AS            
BEGIN              
              
  create table #Tmp_SysAccount(            
 Item1               varchar(64),            
 Item1Count          int,            
 Item2               varchar(64),            
 Item2Value          numeric(18,2),            
 Item3               varchar(64),            
 Item3Value          numeric(18,2),      
 Item4               varchar(64),            
 Item4Value          int              
 )         
      
 CREATE TABLE #T_C_SysAccontdDay       
 (        
 fOldAcount int not null,        --原账户人数      
 fOldAcountMoney numeric(19,2),  --原账户余额      
 fConsCount int not null,        --营业人数      
 fConsMoney  numeric(19,2),      --营业金额      
 fkhCount    int not null ,      --开户人数      
 fKhtlSum    numeric(19,2),      --开户金额      
 fKhDpsit    numeric(19,2),      --开户押金      
 fKhPndge    numeric(19,2),      --开户卡费      
 fKhManage   numeric(19,2),      --开户管理费      
 fChCount    int not null ,      --撤户人数      
 fChtlSum    numeric(19,2),      --撤户金额      
 fChPndge    numeric(19,2),      --撤户手续费      
 fChMoney    numeric(19,2),      --应退押金      
 fChTkMoney  numeric(19,2),      --退款金额       
 fSvCount    int not null ,      --存款人数      
 fSvtlSum    numeric(19,2),      --存款金额        
 fSvPndge    numeric(19,2),      --存款管理费         
 fTkCount    int not null ,      --取款人数      
 fTktlSum    numeric(19,2),      --取款金额      
 fGsCount    int not null ,      --挂失人数        
 fGsPndge    numeric(19,2),      --挂失手续费        
 fJgCount    int not null ,      --解挂人数        
 fJgPndge    numeric(19,2),      --解挂手续费       
 fHkCount    int not null ,      --换卡人数      
 fHkPndge    numeric(19,2),      --换卡手续费      
 fBkCount    int not null ,      --补卡人数       
 fBktlSum    numeric(19,2),      --补卡卡费      
 fBkPndge    numeric(19,2),      --补卡手续费      
 fJcCount    int not null ,      --纠错人数      
 fJctlSum    numeric(19,2),      --纠错金额      
 fSbCount    int    not null,    --补助人数      
 fSbtlSum    numeric(19,2),      --补助金额      
 fSbClearCount  int    not null, --补助清零人数      
 fSbClearSum    numeric(19,2),   --补助清零金额      
 fQCCount    int    not null,    --圈存人数      
 fQCtlSum    numeric(19,2),      --圈存金额      
 fQCBXCount  int not null ,      --圈存补款人数      
 fQCBXtlSum    numeric(19,2),    --圈存补款金额      
 fNewAcount int not null,        --现账户人数      
 fNewAcountMoney numeric(19,2),  --现账户余额   
   
 [fOldAcountMoneyJC]int, --原账户金额(计次)  
 [fNewAcountMoneyJC]int, --现账户金额(计次)  
 [fConsMoneyJC]int,      --消费金额(计次)  
 fSbCountJC    int    not null,    --补助人数(计次)      
 fSbtlSumJC    int,      --补助金额(计次)      
 fSbClearCountJC  int    not null, --补助清零人数(计次)      
 fSbClearSumJC    int,   --补助清零金额(计次)   
 fJcCountJC    int not null ,      --纠错人数(计次)      
 fJctlSumJC    int,      --纠错金额(计次)      
 fSvCountJC     int not null ,     --存款人数(计次)      
 fSvtlSumJC     int,     --存款金额(计次)          
 fTkCountJC     int not null ,     --取款人数(计次)      
 fTktlSumJC     int      --取款金额(计次)   
 )      
 if  @EndDate=CONVERT(varchar(10),GETDATE(),120)    
 begin       
 delete from T_C_SysAccontdToDay      
 exec UP_MakeSysAccontByday  @EndDate      
 end 
 else
 delete from T_C_SysAccontdToDay  where fDate<GETDATE()  
 
 insert into #T_C_SysAccontdDay       
       
 select SUM([fOldAcount])fOldAcount,SUM([fOldAcountMoney]) fOldAcountMoney, sum([fConsCount])[fConsCount], sum([fConsMoney])[fConsMoney], sum([fkhCount])[fkhCount], sum([fKhtlSum])[fKhtlSum],      
  sum([fKhDpsit])[fKhDpsit], sum([fKhPndge])[fKhPndge], sum([fKhManage])[fKhManage], sum([fChCount])[fChCount], sum([fChtlSum])[fChtlSum], sum([fChPndge])[fChPndge],       
  sum([fChMoney])[fChMoney], sum([fChTkMoney])[fChTkMoney], sum([fSvCount])[fSvCount], sum([fSvtlSum])[fSvtlSum], sum([fSvPndge])[fSvPndge], sum([fTkCount])[fTkCount],      
  sum([fTktlSum])[fTktlSum], sum([fGsCount])[fGsCount], sum([fGsPndge])[fGsPndge], sum([fJgCount])[fJgCount], sum([fJgPndge])[fJgPndge], sum([fHkCount])[fHkCount],      
  sum([fHkPndge])[fHkPndge], sum([fBkCount])[fBkCount], sum([fBktlSum])[fBktlSum], sum([fBkPndge])[fBkPndge], sum([fJcCount])[fJcCount], sum([fJctlSum])[fJctlSum],      
  sum([fSbCount])[fSbCount], sum([fSbtlSum])[fSbtlSum], sum([fSbClearCount])[fSbClearCount],sum([fSbClearSum])[fSbClearSum], sum([fQCCount])[fQCCount], sum([fQCtlSum])[fQCtlSum],      
  sum([fQCBXCount])[fQCBXCount], sum([fQCBXtlSum])[fQCBXtlSum], SUM([fNewAcount]) [fNewAcount],SUM([fNewAcountMoney]) [fNewAcountMoney],  
  sum([fOldAcountMoneyJC]) [fOldAcountMoneyJC],sum([fNewAcountMoneyJC])[fNewAcountMoneyJC],sum([fConsMoneyJC]) [fConsMoneyJC] ,  
  SUM([fSbCountJC]) [fSbCountJC],SUM([fSbtlSumJC])[fSbtlSumJC],SUM([fSbClearCountJC])[fSbClearCountJC],SUM([fSbClearSumJC]) [fSbClearSumJC],  
  SUM([fJcCountJC])fJcCountJC,SUM([fJctlSumJC]) fJctlSumJC,  
  SUM([fSvCountJC]) AS fSvCountJC, SUM([fSvtlSumJC]) AS  fSvtlSumJC,SUM([fTkCountJC]) AS   fTkCountJC,SUM([fTktlSumJC]) AS   fTktlSumJC   
      
 from (       
       
 select  * from (      
 select top 1  [fOldAcount],[fOldAcountMoney], 0 as [fConsCount], 0 as [fConsMoney], 0 as [fkhCount], 0 as [fKhtlSum], 0 as [fKhDpsit], 0 as [fKhPndge], 0 as [fKhManage]      
      , 0 as [fChCount], 0 as [fChtlSum], 0 as [fChPndge], 0 as [fChMoney], 0 as [fChTkMoney], 0 as [fSvCount], 0 as [fSvtlSum], 0 as [fSvPndge], 0 as [fTkCount]      
      , 0 as [fTktlSum], 0 as [fGsCount], 0 as [fGsPndge], 0 as [fJgCount], 0 as [fJgPndge], 0 as [fHkCount], 0 as [fHkPndge], 0 as [fBkCount], 0 as [fBktlSum]      
      , 0 as [fBkPndge], 0 as [fJcCount], 0 as [fJctlSum], 0 as [fSbCount], 0 as [fSbtlSum], 0 as [fSbClearCount], 0 as [fSbClearSum], 0 as [fQCCount], 0 as [fQCtlSum]      
      , 0 as [fQCBXCount], 0 as [fQCBXtlSum], 0 as [fNewAcount], 0 as [fNewAcountMoney],  
       [fOldAcountMoneyJC],0 as [fNewAcountMoneyJC], 0 as [fConsMoneyJC],  
       0 as [fSbCountJC],0 as [fSbtlSumJC],0 as [fSbClearCountJC],0 as [fSbClearSumJC],0 as  [fJcCountJC], 0 as [fJctlSumJC],  
       0 AS [fSvCountJC],0 as [fSvtlSumJC],0 as [fTkCountJC],0 as [fTktlSumJC]  
       from (select  * from T_C_SysAccontdDay union all select  * from T_C_SysAccontdToDay) a where       
 convert(varchar(10),fDate,120)>=@BeginDate and convert(varchar(10),fDate,120)<=@EndDate order by fDate ) a      
 union all      
  select  * from (      
 select top 1  0 as [fOldAcount],0 as [fOldAcountMoney], 0 as [fConsCount], 0 as [fConsMoney], 0 as [fkhCount], 0 as [fKhtlSum], 0 as [fKhDpsit], 0 as [fKhPndge], 0 as [fKhManage]      
      , 0 as [fChCount], 0 as [fChtlSum], 0 as [fChPndge], 0 as [fChMoney], 0 as [fChTkMoney], 0 as [fSvCount], 0 as [fSvtlSum], 0 as [fSvPndge], 0 as [fTkCount]      
      , 0 as [fTktlSum], 0 as [fGsCount], 0 as [fGsPndge], 0 as [fJgCount], 0 as [fJgPndge], 0 as [fHkCount], 0 as [fHkPndge], 0 as [fBkCount], 0 as [fBktlSum]      
      , 0 as [fBkPndge], 0 as [fJcCount], 0 as [fJctlSum], 0 as [fSbCount], 0 as [fSbtlSum], 0 as [fSbClearCount], 0 as [fSbClearSum], 0 as [fQCCount], 0 as [fQCtlSum]      
      , 0 as [fQCBXCount], 0 as [fQCBXtlSum], [fNewAcount],[fNewAcountMoney],  
      0 as [fOldAcountMoneyJC],  [fNewAcountMoneyJC], 0 as [fConsMoneyJC],  
      0 as [fSbCountJC],0 as [fSbtlSumJC],0 as [fSbClearCountJC],0 as [fSbClearSumJC],0 as  [fJcCountJC], 0 as [fJctlSumJC],  
      0 AS [fSvCountJC],0 as [fSvtlSumJC],0 as [fTkCountJC],0 as [fTktlSumJC]  
       from (select  * from T_C_SysAccontdDay union all select  * from T_C_SysAccontdToDay) a  where       
 convert(varchar(10),fDate,120)>=@BeginDate and convert(varchar(10),fDate,120)<=@EndDate order by fDate desc) a      
       
 union all      
       
 select 0 as fOldAcount,0 as fOldAcountMoney, sum([fConsCount])[fConsCount], sum([fConsMoney])[fConsMoney], sum([fkhCount])[fkhCount], sum([fKhtlSum])[fKhtlSum],      
  sum([fKhDpsit])[fKhDpsit], sum([fKhPndge])[fKhPndge], sum([fKhManage])[fKhManage], sum([fChCount])[fChCount], sum([fChtlSum])[fChtlSum], sum([fChPndge])[fChPndge],       
  sum([fChMoney])[fChMoney], sum([fChTkMoney])[fChTkMoney], sum([fSvCount])[fSvCount], sum([fSvtlSum])[fSvtlSum], sum([fSvPndge])[fSvPndge], sum([fTkCount])[fTkCount],      
  sum([fTktlSum])[fTktlSum], sum([fGsCount])[fGsCount], sum([fGsPndge])[fGsPndge], sum([fJgCount])[fJgCount], sum([fJgPndge])[fJgPndge], sum([fHkCount])[fHkCount],      
  sum([fHkPndge])[fHkPndge], sum([fBkCount])[fBkCount], sum([fBktlSum])[fBktlSum], sum([fBkPndge])[fBkPndge], sum([fJcCount])[fJcCount], sum([fJctlSum])[fJctlSum],      
  sum([fSbCount])[fSbCount], sum([fSbtlSum])[fSbtlSum], sum([fSbClearCount])[fSbClearCount],sum([fSbClearSum])[fSbClearSum], sum([fQCCount])[fQCCount], sum([fQCtlSum])[fQCtlSum],      
  sum([fQCBXCount])[fQCBXCount], sum([fQCBXtlSum])[fQCBXtlSum], 0 as [fNewAcount],0 as [fNewAcountMoney],  
  0 as  [fOldAcountMoneyJC],0 as [fNewAcountMoneyJC],sum([fConsMoneyJC]) [fConsMoneyJC] ,  
  SUM([fSbCountJC]) [fSbCountJC],SUM([fSbtlSumJC]) as [fSbtlSumJC],SUM([fSbClearCountJC]) as [fSbClearCountJC],  
  SUM([fSbClearSumJC]) as [fSbClearSumJC],SUM([fJcCountJC]) as  [fJcCountJC], SUM([fJctlSumJC]) as [fJctlSumJC],  
  SUM([fSaveCountJC]) AS fSvCountJC, SUM([fSaveMoneyJC]) AS  fSvtlSumJC,SUM([fTakeCountJC]) AS   fTkCountJC,SUM([fTakeMoneyJC]) AS   fTktlSumJC  
   from (select  * from T_C_SysAccontdDay union all select  * from T_C_SysAccontdToDay) a        
where convert(varchar(10),fDate,120)>=@BeginDate and convert(varchar(10),fDate,120)<=@EndDate  )t      
   
 insert into #Tmp_SysAccount    select  '原账户人数'   ,fOldAcount    ,'原账户余额'   ,fOldAcountMoney ,null           ,null       ,'原账户余额(计次)'   ,[fOldAcountMoneyJC] from #T_C_SysAccontdDay        
 insert into #Tmp_SysAccount    select  '营业人次'     ,fConsCount    ,'营业金额'     ,fConsMoney      ,null           ,null       ,'营业金额(计次)'     ,[fConsMoneyJC] from #T_C_SysAccontdDay    
 insert into #Tmp_SysAccount    select  '开户人数'     ,fkhCount      ,'开户金额'     ,fKhtlSum        ,'开户押金'     ,fKhDpsit   ,null                 ,null from #T_C_SysAccontdDay      
      
 insert into #Tmp_SysAccount    select  null           ,null          ,'开户卡费'     ,fKhPndge        ,'开户管理费'   ,fKhManage  ,null                 ,null from #T_C_SysAccontdDay          
  
 insert into #Tmp_SysAccount    select  '撤户人数'     ,fChCount      ,'撤户余额'     ,fChtlSum        ,'撤户手续费'   ,fChPndge   ,'充值人次(计次)'     ,fSvCountJC from #T_C_SysAccontdDay          
        
 insert into #Tmp_SysAccount    select   null          ,null          ,'应退押金'     ,fChMoney        ,'退款金额'     ,fChTkMoney ,'充值金额(计次)'     ,fSvtlSumJC from #T_C_SysAccontdDay   
  
 insert into #Tmp_SysAccount    select  '存款人数'     ,fSvCount      ,'存款金额'     ,fSvtlSum        ,'存款管理费'   ,fSvPndge   ,'取款人次(计次)'     ,fTkCountJC from #T_C_SysAccontdDay    
 insert into #Tmp_SysAccount    select  '取款人数'     ,fTkCount      ,'取款金额'     ,fTktlSum        ,null           ,null       ,'取款金额(计次)'     ,fTktlSumJC from #T_C_SysAccontdDay    
 insert into #Tmp_SysAccount    select  '挂失人数'     ,fGsCount      ,'挂失手续费'   ,fGsPndge        ,null           ,null       ,'纠错人数(计次)'     ,fJcCountJC from #T_C_SysAccontdDay   
 insert into #Tmp_SysAccount    select  '解挂人数'     ,fJgCount      ,'解挂手续费'   ,fJgPndge        ,null           ,null       ,'纠错金额(计次)'     ,fJctlSumJC from #T_C_SysAccontdDay    
 insert into #Tmp_SysAccount    select  '换卡人数'     ,fHkCount      ,'换卡手续费'   ,fHkPndge        ,null           ,null       ,'补助人数(计次)'     ,fSbCountJC from #T_C_SysAccontdDay  
 insert into #Tmp_SysAccount    select  '补卡人数'     ,fBkCount      ,'补卡卡费'     ,fBktlSum        ,'补卡手续费'   ,fBkPndge   ,'补助金额(计次)'     ,fSbtlSumJC from #T_C_SysAccontdDay          
 insert into #Tmp_SysAccount    select  '纠错人数'     ,fJcCount      ,'纠错金额'     ,fJctlSum        ,null           ,null       ,'补助清零人数(计次)' ,fSbClearCountJC from #T_C_SysAccontdDay    
 insert into #Tmp_SysAccount    select  '补助人数'     ,fSbCount      ,'补助金额'     ,fSbtlSum        ,null           ,null       ,'补助清零金额(计次)' ,fSbClearSumJC from #T_C_SysAccontdDay   
 insert into #Tmp_SysAccount    select  '补助清零人数' ,fSbClearCount ,'补助清零金额' ,fSbClearSum     ,null           ,null       ,null                 ,null from #T_C_SysAccontdDay    
 insert into #Tmp_SysAccount    select  '圈存人数'     ,fQCCount      ,'圈存金额'     ,fQCtlSum        ,null           ,null       ,null                 ,null from #T_C_SysAccontdDay          
 insert into #Tmp_SysAccount    select  '圈存补款人数' ,fQCBXCount    ,'圈存补款金额' ,fQCBXtlSum      ,null           ,null       ,null                 ,null from #T_C_SysAccontdDay     
 insert into #Tmp_SysAccount    select  '现账户人数'   ,fNewAcount    ,'现账户余额'   ,fNewAcountMoney ,null           ,null       ,'现账户余额(计次)'   ,[fNewAcountMoneyJC] from #T_C_SysAccontdDay       
              
 select Item1 [项目1],      
 Item1Count [项目1数量],       
 Item2 [项目2],        
 Item2Value [项目2金额] ,      
 Item3 [项目3],        
 Item3Value [项目3金额],        
 Item4 [项目4],        
 Item4Value [项目4金额]         
 from #Tmp_SysAccount      
 drop table #Tmp_SysAccount      
END    
GO

--REPORT_EDIT_11 修改出纳阶段报表（按钱包）UP_Report_Cns_Total_CashStagedByPurse  

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UP_Report_Cns_Total_CashStagedByPurse]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[UP_Report_Cns_Total_CashStagedByPurse]
GO
create procedure [dbo].[UP_Report_Cns_Total_CashStagedByPurse] @STATIONID  varchar(2),     -- 工作站  
      @oper_id  varchar(1024),   --操作员ID  
      @BegDateTime varchar(20),     --查询开始日期；yyyy-mm-dd  
      @EndDateTime varchar(20),     --查询结束日期；yyyy-mm-dd  
      @AppID varchar(200)         --钱包选择 
      as  
begin  
declare @SQLSTR varchar(8000)  
DECLARE @strB varchar(30),  
  @strE varchar(30)  
SET @strB = CONVERT(varchar(20), @BegDateTime, 23) + ' 00:00:00'  
SET @strE = CONVERT(varchar(20), @EndDateTime, 23) + ' 23:59:59'  
--print @strB  
--print @strE  
set @sqlstr =   
'SELECT  b.fOperName as [操作员],c.fPurseName as [钱包名称]  
 --, SUM([消费|次]) as [消费|次], SUM([消费|金额]) as [消费|金额]  
 , SUM([金额充值|次]) as [金额充值|次], SUM([金额充值|金额]) as [金额充值|金额]
 , SUM([次数充值|次]) as [次数充值|次], SUM([次数充值|金额]) as [次数充值|金额]
 , SUM([存款|管理费]) as [存款|管理费]
 , SUM([金额取款|次]) as [金额取款|次], SUM([金额取款|金额]) as [金额取款|金额]
 , SUM([次数取款|次]) as [次数取款|次], SUM([次数取款|金额]) as [次数取款|金额]
 , SUM([金额补助|次]) as [金额补助|次], SUM([金额补助|金额]) as [金额补助|金额]
 , SUM([次数补助|次]) as [次数补助|次], SUM([次数补助|金额]) as [次数补助|金额] 
 , SUM([挂失|次]) as [挂失|次], SUM([挂失|金额]) as [挂失|金额], SUM([挂失|手续费]) as [挂失|手续费]  
 , SUM([解挂|次]) as [解挂|次], SUM([解挂|金额]) as [解挂|金额], SUM([解挂|手续费]) as [解挂|手续费]  
 , SUM([开户|次]) as [开户|次], SUM([开户|金额]) as [开户|金额], SUM([开户|卡费]) as [开户|卡费], SUM([开户|押金]) as [开户|押金], SUM([开户|管理费]) as [开户|管理费]  
 , SUM([有卡撤户|次]) as [有卡撤户|次], SUM([有卡撤户|金额]) as [有卡撤户|金额], SUM([有卡撤户|手续费]) as [有卡撤户|手续费], SUM([有卡撤户|押金]) as [有卡撤户|押金]  
 , SUM([纠错|次]) as [纠错|次], SUM([纠错|金额]) as [纠错|金额]  
 , SUM([换卡|次]) as [换卡|次], SUM([换卡|金额]) as [换卡|金额], SUM([换卡|手续费]) as [换卡|手续费]  
 , SUM([补卡|次]) as [补卡|次], SUM([补卡|金额]) as [补卡|金额], SUM([补卡|手续费]) as [补卡|手续费], SUM([补卡|卡费]) as [补卡|卡费]  
 , SUM([有卡变更|次]) as [有卡变更|次], SUM([有卡变更|金额]) as [有卡变更|金额]  
 --, SUM([自动挂失|次]) as [自动挂失|次], SUM([自动挂失|金额]) as [自动挂失|金额]  
 --, SUM([无卡变更|次]) as [无卡变更|次], SUM([无卡变更|金额]) as [无卡变更|金额]  
 , SUM([人工冻结|次]) as [人工冻结|次], SUM([人工冻结|金额]) as [人工冻结|金额]  
 --, SUM([自动冻结|次]) as [自动冻结|次], SUM([自动冻结|金额]) as [自动冻结|金额]  
 , SUM([无卡撤户|次]) as [无卡撤户|次], SUM([无卡撤户|金额]) as [无卡撤户|金额], SUM([无卡撤户|手续费]) as [无卡撤户|手续费], SUM([无卡撤户|押金]) as [无卡撤户|押金]  
 , SUM([补发卡|次]) as [补发卡|次], SUM([补发卡|金额]) as [补发卡|金额]  
 , SUM([解冻|次]) as [解冻|次], SUM([解冻|金额]) as [解冻|金额]  
 --, SUM([圈存|次]) as [圈存|次], SUM([圈存|金额]) as [圈存|金额], SUM([圈存|管理费]) as [圈存|管理费]  
 --, SUM([圈存补款|次]) as [圈存补款|次], SUM([圈存补款|金额]) as [圈存补款|金额]  
 --, SUM([圈提|次]) as [圈提|次], SUM([圈提|金额]) as [圈提|金额]   
 --, SUM([优惠|次]) as [优惠|次], SUM([优惠|金额]) as [优惠|金额]  
 --, SUM([计次|次]) as [计次|次], SUM([计次|金额]) as [计次|金额]  
 --, SUM([转入|次]) as [转入|次], SUM([转入|金额]) as [转入|金额]  
 --, SUM([转出|次]) as [转出|次], SUM([转出|金额]) as [转出|金额]  
 --, SUM([删除资料|次]) as [删除资料|次], SUM([删除资料|金额]) as [删除资料|金额]  
 , SUM([销卡|次]) as [销卡|次], SUM([销卡|金额]) as [销卡|金额]  
 , (SUM([金额充值|次])+SUM([金额取款|次])+SUM([金额补助|次])+SUM([挂失|次])+SUM([解挂|次])+SUM([开户|次])+SUM([有卡撤户|次])+  
    SUM([纠错|次])+SUM([换卡|次])+SUM([补卡|次])+SUM([有卡变更|次])+SUM([自动挂失|次])+SUM([无卡变更|次])+  
    SUM([人工冻结|次])+SUM([自动冻结|次])+SUM([无卡撤户|次])+SUM([补发卡|次])+SUM([解冻|次])+SUM([圈存|次])+  
    SUM([圈存补款|次])+SUM([圈提|次])+SUM([优惠|次])+SUM([计次|次])+SUM([转入|次])+SUM([转出|次])+SUM([删除资料|次])+  
    SUM([销卡|次])) as [发生总人数]  
 , SUM([开户|金额])+SUM([开户|卡费])+SUM([开户|押金])+SUM([开户|管理费])+  
   SUM([有卡撤户|手续费])-SUM([有卡撤户|金额])-SUM([有卡撤户|押金])+  
   SUM([无卡撤户|手续费])-SUM([无卡撤户|金额])-SUM([无卡撤户|押金])+  
   SUM([金额充值|金额])+SUM([存款|管理费])-SUM([金额取款|金额]) as [上缴总金额]  
   FROM V_C_SUM_OPER a left join T_B_Manager B on A.fOperID = b.fOperID ' + char(13) +  
   ' left join t_b_pursecode c on a.fAppID=c.fPurseCode'+
   ' where fDate >= ''' + @strB + ''' and fDate <= ''' + @strE + ''' '  
if(@STATIONID <> '')  
  set @sqlstr = + @sqlstr + ' and b.fStationId like (''' + @STATIONID +'%'') '  
if(@oper_id <> '')  
  set @sqlstr = + @sqlstr + ' and ' + @oper_id   
 if @AppID<>''
 set  @sqlstr = + @sqlstr + ' and ' + @AppID   
  
set @sqlstr = @sqlstr + char(13) + 'group by a.fOperID,b.fOperName,c.fPurseCode,c.fPurseName'  
 print @sqlstr  
 exec(@sqlstr)  
end

GO
 
--REPORT_EDIT_12 修改报表UP_Report_Cns_Total_CashMonthDay 

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UP_Report_Cns_Total_CashMonthDay]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[UP_Report_Cns_Total_CashMonthDay]
GO
create procedure [dbo].[UP_Report_Cns_Total_CashMonthDay] @STATIONID varchar(2),     -- 工作站
      @oper_id  varchar(1024),   --操作员ID
      @Year varchar(4),          --查询年份；yyyy
      @Month varchar(2)         --查询月份；mm 
      as
begin
declare @sqlstr varchar(8000)
DECLARE @Begin datetime,
        @end   datetime,
        @strB varchar(30),
		@strE varchar(30)
/*        ,@Year varchar(4)
        ,@Month varchar(2) 
     set  @Year = '2013'   
     set  @Month = '04'*/
SET @Begin = @Year + '-' + dbo.fn_FillZero(2,@Month) + '-01 00:00:00'
SET @end = @Year + '-' + dbo.fn_FillZero(2,@Month) + '-' + cast(32-Day(@Begin+(32-Day(@Begin))) as varchar(2)) + ' 23:59:59'
--print @Begin
--print @end
SET @strB = CONVERT(varchar(100), @Begin, 20)
SET @strE = CONVERT(varchar(100), @end, 20)
--print @strB
--print @strE
set @sqlstr = 
'SELECT  CONVERT(varchar(20), a.fDate, 23) as [日期]
	--, SUM([消费|次]) as [消费|次], SUM([消费|金额]) as [消费|金额]
	 , SUM([金额充值|次]) as [金额充值|次], SUM([金额充值|金额]) as [金额充值|金额]
	 , SUM([次数充值|次]) as [次数充值|次], SUM([次数充值|金额]) as [次数充值|金额]
	 , SUM([存款|管理费]) as [存款|管理费]
	 , SUM([金额取款|次]) as [金额取款|次], SUM([金额取款|金额]) as [金额取款|金额]
	 , SUM([次数取款|次]) as [次数取款|次], SUM([次数取款|金额]) as [次数取款|金额]
	 , SUM([金额补助|次]) as [金额补助|次], SUM([金额补助|金额]) as [金额补助|金额]
	 , SUM([次数补助|次]) as [次数补助|次], SUM([次数补助|金额]) as [次数补助|金额]
	, SUM([挂失|次]) as [挂失|次], SUM([挂失|金额]) as [挂失|金额], SUM([挂失|手续费]) as [挂失|手续费]
	, SUM([解挂|次]) as [解挂|次], SUM([解挂|金额]) as [解挂|金额], SUM([解挂|手续费]) as [解挂|手续费]
	, SUM([开户|次]) as [开户|次], SUM([开户|金额]) as [开户|金额], SUM([开户|卡费]) as [开户|卡费], SUM([开户|押金]) as [开户|押金], SUM([开户|管理费]) as [开户|管理费]
	, SUM([有卡撤户|次]) as [有卡撤户|次], SUM([有卡撤户|金额]) as [有卡撤户|金额], SUM([有卡撤户|手续费]) as [有卡撤户|手续费], SUM([有卡撤户|押金]) as [有卡撤户|押金]
	, SUM([纠错|次]) as [纠错|次], SUM([纠错|金额]) as [纠错|金额]
	, SUM([换卡|次]) as [换卡|次], SUM([换卡|金额]) as [换卡|金额], SUM([换卡|手续费]) as [换卡|手续费]
	, SUM([补卡|次]) as [补卡|次], SUM([补卡|金额]) as [补卡|金额], SUM([补卡|手续费]) as [补卡|手续费], SUM([补卡|卡费]) as [补卡|卡费]
	, SUM([有卡变更|次]) as [有卡变更|次], SUM([有卡变更|金额]) as [有卡变更|金额]
	--, SUM([自动挂失|次]) as [自动挂失|次], SUM([自动挂失|金额]) as [自动挂失|金额]
	--, SUM([无卡变更|次]) as [无卡变更|次], SUM([无卡变更|金额]) as [无卡变更|金额]
	, SUM([人工冻结|次]) as [人工冻结|次], SUM([人工冻结|金额]) as [人工冻结|金额]
	--, SUM([自动冻结|次]) as [自动冻结|次], SUM([自动冻结|金额]) as [自动冻结|金额]
	, SUM([无卡撤户|次]) as [无卡撤户|次], SUM([无卡撤户|金额]) as [无卡撤户|金额], SUM([无卡撤户|手续费]) as [无卡撤户|手续费], SUM([无卡撤户|押金]) as [无卡撤户|押金]
	, SUM([补发卡|次]) as [补发卡|次], SUM([补发卡|金额]) as [补发卡|金额]
	, SUM([解冻|次]) as [解冻|次], SUM([解冻|金额]) as [解冻|金额]
	--, SUM([圈存|次]) as [圈存|次], SUM([圈存|金额]) as [圈存|金额], SUM([圈存|管理费]) as [圈存|管理费]
	--, SUM([圈存补款|次]) as [圈存补款|次], SUM([圈存补款|金额]) as [圈存补款|金额]
	--, SUM([圈提|次]) as [圈提|次], SUM([圈提|金额]) as [圈提|金额] 
	--, SUM([优惠|次]) as [优惠|次], SUM([优惠|金额]) as [优惠|金额]
	--, SUM([计次|次]) as [计次|次], SUM([计次|金额]) as [计次|金额]
	--, SUM([转入|次]) as [转入|次], SUM([转入|金额]) as [转入|金额]
	--, SUM([转出|次]) as [转出|次], SUM([转出|金额]) as [转出|金额]
	--, SUM([删除资料|次]) as [删除资料|次], SUM([删除资料|金额]) as [删除资料|金额]
	, SUM([销卡|次]) as [销卡|次], SUM([销卡|金额]) as [销卡|金额]
	, (SUM([金额充值|次])+SUM([金额取款|次])+SUM([金额补助|次])+SUM([挂失|次])+SUM([解挂|次])+SUM([开户|次])+SUM([有卡撤户|次])+
	   SUM([纠错|次])+SUM([换卡|次])+SUM([补卡|次])+SUM([有卡变更|次])+SUM([自动挂失|次])+SUM([无卡变更|次])+
	   SUM([人工冻结|次])+SUM([自动冻结|次])+SUM([无卡撤户|次])+SUM([补发卡|次])+SUM([解冻|次])+SUM([圈存|次])+
	   SUM([圈存补款|次])+SUM([圈提|次])+SUM([优惠|次])+SUM([计次|次])+SUM([转入|次])+SUM([转出|次])+SUM([删除资料|次])+
	   SUM([销卡|次])) as [发生总人数]
	, SUM([开户|金额])+SUM([开户|卡费])+SUM([开户|押金])+SUM([开户|管理费])+
	  SUM([有卡撤户|手续费])-SUM([有卡撤户|金额])-SUM([有卡撤户|押金])+
	  SUM([无卡撤户|手续费])-SUM([无卡撤户|金额])-SUM([无卡撤户|押金])+
	  SUM([金额充值|金额])+SUM([存款|管理费])-SUM([金额取款|金额]) as [上缴总金额]
	  FROM V_C_SUM_OPER a left join T_B_Manager B on A.fOperID = b.fOperID ' + char(13) +
   ' where fDate >= ''' + @strB + ''' and fDate <= ''' + @strE + ''' '
if(@STATIONID <> '')
  set @sqlstr = + @sqlstr + ' and b.fStationId like (''' + @STATIONID +'%'') '
if(@oper_id <> '')
  set @sqlstr = + @sqlstr + ' and ' + @oper_id 

set @sqlstr = @sqlstr + char(13) +
              'group by CONVERT(varchar(20), a.fDate, 23)'
 print @sqlstr
 exec(@sqlstr)
end
GO

--REPORT_EDIT_13 修改报表UP_Report_detail_OperatorLog

IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UP_Report_detail_OperatorLog]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[UP_Report_detail_OperatorLog]
GO
CREATE procedure [dbo].[UP_Report_detail_OperatorLog] @STATIONID   varchar(2),  -- 工作站；传值，工作站名称，只能传入一个工作站名称  
      @BegDateTime varchar(20),  --开始查询日期  
      @EndDateTime varchar(20),  --结束查询日  
      @OperID    varchar(20)     --操作员编号,为空查询所有操作员   
      as  
BEGIN  
 declare @STRSQL varchar(8000),  
   @Where nvarchar(1000),  
   @iRet int,  
   @sRet varchar(300),  
   @strB varchar(30),  
   @strE varchar(30),  
   @StrSTA varchar(50),  
   @StrOPR varchar(50)  
 SET @strB = CONVERT(varchar(20), @BegDateTime, 23) + ' 00:00:00'  
 SET @strE = CONVERT(varchar(20), @EndDateTime, 23) + ' 23:59:59'  
  
 EXEC UP_R_CheckTime @strB, @strE, 1, @iRet output, @sRet output  
 if @iRet = -9999 OR @sRet = ''  
  SET @STRSQL = 'SELECT ''查询表无效-查询表范围超期'' AS [返回信息]'  
 ELSE  
 BEGIN  
   IF (@STATIONID<>'')  
  SET @StrSTA = ' AND R.fSiteID like ''' + @STATIONID + '%'' '+ char(13)  
   ELSE  
  SET @StrSTA = ''  
   if (@OperID<>'')  
  SET @StrOPR = ' AND R.fOperID = '''  +  @OperID + ''' '+ char(13)  
   ELSE  
  SET @StrOPR = ''  
  
 set @STRSQL =   
	' select  
   b.fName as 姓名, 
   c.fDeptName as 部门名称, 
   R.fAccountID as 帐号,  
   R.fSerialNo as 卡号,  
   c.fDeptCode 部门代码,  
   R.fOldBalance as [原余额], 
   R.fAmount [发生额], 
   R.fNewBalance as [现余额], 
   R.fFee1 as [手续费],
   R.fFee2 as [卡费], 
   R.fFee3 [押金], 
   R.fFee4 [管理费], 
   f.fStateName as 操作类型, 
   R.fCreateTime as 发生时间,
   R.fPosID as 机号,  
   d.fPosName as 设备名称,  
   e.fOperName as 操作员 
 from 
 '+@sRet+'
 left join T_B_Employee b on R.fAccountid = b.fAccountID 
 left join T_B_Dept c on b.fDept = c.fDeptCode 
 left join T_B_Pos d on R.fPosID = d.fPosID 
 left join T_B_Manager e on R.fOperID = e.fOperID  
 left join T_C_ConsState f on R.fRecType = f.fStateID '+ 
 ' where R.fSettleTime >= ''' + @strB + ''' and ' +  char(13) +  
 '  R.fSettleTime <= ''' + @strE + ''' ' +  char(13) +  
 @StrSTA + @StrOPR +' ORDER BY R.fSettleTime ,R.fAccountID '  
 END  
  print @STRSQL  
  exec(@STRSQL)  
END  
GO

