/*==============================================================*/
/* 2022-07-28 Edit                                              */
/* PlatScriptVersion :    20220728110256                        */
/* ReportScriptVersion :  20210604173200                        */
/*==============================================================*/



create function dbo.FN_GetPosType (@PosTypeID int)
RETURNS varchar(20) 
AS  
BEGIN 
	return CASE 
	WHEN @PosTypeID=0 THEN '考勤机'
	WHEN @PosTypeID=1 THEN '消费机'
	WHEN @PosTypeID=2 THEN '门禁机'
	WHEN @PosTypeID=3 THEN '读卡器'
	WHEN @PosTypeID=4 THEN '水控机'
	WHEN @PosTypeID=5 THEN '出纳机'
	WHEN @PosTypeID=6 THEN '开户出纳机'
	WHEN @PosTypeID=8 THEN '控制转换器'
	WHEN @PosTypeID=9 THEN '指纹考勤机'
	ELSE ''
	END 
END
go

/*==============================================================*/
/* Table: T_A_CheckCardRules                                    */
/*==============================================================*/
create table dbo.T_A_CheckCardRules (
   fChkCRID             tinyint              not null,
   fGroupBegin          tinyint              not null constraint DF__T_A_Check__fGrou__1C5231C2 default (0),
   fGroupEnd            tinyint              not null constraint DF__T_A_Check__fGrou__1D4655FB default (255),
   fTimeBegin           varchar(5)           collate Chinese_PRC_CI_AS not null constraint DF__T_A_Check__fTime__1E3A7A34 default '(00:00)',
   fTimeEnd             varchar(5)           collate Chinese_PRC_CI_AS not null constraint DF__T_A_Check__fTime__1F2E9E6D default '(24:00)',
   fRingCount           smallint             not null constraint DF__T_A_Check__fRing__2022C2A6 default (1),
   fRingTime            smallint             not null constraint DF__T_A_Check__fRing__2116E6DF default (0)
)
on "PRIMARY"
go

alter table dbo.T_A_CheckCardRules
   add constraint PK__T_A_CheckCardRul primary key (fChkCRID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_A_CheckGroup                                        */
/*==============================================================*/
create table dbo.T_A_CheckGroup (
   fGroupCode           smallint             not null,
   fGroupName           varchar(20)          collate Chinese_PRC_CI_AS not null
)
on "PRIMARY"
go

alter table dbo.T_A_CheckGroup
   add constraint PK_T_A_CheckGroup primary key (fGroupCode)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_A_CheckRule                                         */
/*==============================================================*/
create table dbo.T_A_CheckRule (
   fCheckSystemCode     varchar(4)           collate Chinese_PRC_CI_AS not null,
   fCheckSystemName     varchar(30)          collate Chinese_PRC_CI_AS not null,
   fAllowOverdue        int                  not null constraint DF__T_A_Check__fAllo__220B0B18 default (0),
   fAllowLeaveEarly     int                  not null constraint DF__T_A_Check__fAllo__22FF2F51 default (0),
   fOnDutyBefore        int                  not null constraint DF__T_A_Check__fOnDu__23F3538A default (0),
   fOnDutyAfter         int                  not null constraint DF__T_A_Check__fOnDu__24E777C3 default (0),
   fOffDutyBefore       int                  not null constraint DF__T_A_Check__fOffD__25DB9BFC default (0),
   fOffDutyAfter        int                  not null constraint DF__T_A_Check__fOffD__26CFC035 default (0),
   fOffDutyLast         int                  not null constraint DF__T_A_Check__fOffD__27C3E46E default (0),
   fOffDutyDeferEnable  bit                  not null constraint DF__T_A_Check__fOffD__28B808A7 default (0),
   fSubtractAbsenceTime bit                  not null constraint DF__T_A_Check__fSubt__29AC2CE0 default (0),
   fOffDayIsWeek        bit                  not null constraint DF__T_A_Check__fOffD__2AA05119 default (0),
   fCheckOffDay         bit                  not null constraint DF__T_A_Check__fChec__2B947552 default (1),
   fOffDay              varchar(150)         collate Chinese_PRC_CI_AS null,
   fOffDayCalcOvertime  bit                  not null constraint DF__T_A_Check__fOffD__2C88998B default (0),
   fCheckOvertime       bit                  not null constraint DF__T_A_Check__fChec__2D7CBDC4 default (0),
   fWorkTimeUnit        smallint             not null constraint DF__T_A_Check__fWork__2E70E1FD default (5),
   fWorkTimeMode        smallint             not null constraint DF__T_A_Check__fWork__2F650636 default (0),
   fOvertimeUnit        smallint             not null constraint DF__T_A_Check__fOver__30592A6F default (30),
   fOverTimeMode        smallint             not null constraint DF__T_A_Check__fOver__314D4EA8 default (0),
   fAbsenceTimeUnit     smallint             not null constraint DF__T_A_Check__fAbse__324172E1 default (1),
   fAbsenceTimeMode     smallint             not null constraint DF__T_A_Check__fAbse__3335971A default (0),
   fLeaveTimeUnit       smallint             not null constraint DF__T_A_Check__fLeav__3429BB53 default (30),
   fLeaveTimeMode       smallint             not null constraint DF__T_A_Check__fLeav__351DDF8C default (0),
   fDayOfAbsentMinutes  smallint             not null constraint DF__T_A_Check__fDayO__361203C5 default (0),
   fDayOfLeaveMinutes   smallint             not null constraint DF__T_A_Check__fDayO__370627FE default (0),
   fMultipleOfNormal    decimal(3,1)         not null constraint DF__T_A_Check__fMult__37FA4C37 default (1),
   fMultipleOfOffDay    decimal(3,1)         not null constraint DF__T_A_Check__fMult__38EE7070 default (1),
   fMultipleOfHoliDay   decimal(3,1)         not null constraint DF__T_A_Check__fMult__39E294A9 default (1),
   fCompulsory          bit                  not null constraint DF__T_A_Check__fComp__3AD6B8E2 default (0),
   fOverTimeDuration    int                  not null constraint DF__T_A_Check__fOver__3BCADD1B default (30),
   fIsDefault           bit                  not null constraint DF__T_A_Check__fIsDe__3CBF0154 default (0)
)
on "PRIMARY"
go

alter table dbo.T_A_CheckRule
   add constraint PK__T_A_CheckRule primary key (fCheckSystemCode)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_A_RecType                                           */
/*==============================================================*/
create table dbo.T_A_RecType (
   fTypeID              int                  not null,
   fTypeName            varchar(50)          collate Chinese_PRC_CI_AS not null
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_A_ReportDays                                        */
/*==============================================================*/
create table dbo.T_A_ReportDays (
   fKeyID               int                  identity(1, 1),
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS not null,
   fCheckDate           datetime             not null,
   fWeekday             varchar(6)           collate Chinese_PRC_CI_AS not null,
   fWorkTimeCode        varchar(4)           collate Chinese_PRC_CI_AS not null,
   fOnDuty1             varchar(5)           collate Chinese_PRC_CI_AS null,
   fOffDuty1            varchar(5)           collate Chinese_PRC_CI_AS null,
   fOnDuty2             varchar(5)           collate Chinese_PRC_CI_AS null,
   fOffDuty2            varchar(5)           collate Chinese_PRC_CI_AS null,
   fOnDuty3             varchar(5)           collate Chinese_PRC_CI_AS null,
   fOffDuty3            varchar(5)           collate Chinese_PRC_CI_AS null,
   fOnDuty4             varchar(5)           collate Chinese_PRC_CI_AS null,
   fOffDuty4            varchar(5)           collate Chinese_PRC_CI_AS null,
   fOnDuty5             varchar(5)           collate Chinese_PRC_CI_AS null,
   fOffDuty5            varchar(5)           collate Chinese_PRC_CI_AS null,
   fOnDuty6             varchar(5)           collate Chinese_PRC_CI_AS null,
   fOffDuty6            varchar(5)           collate Chinese_PRC_CI_AS null,
   fDays                tinyint              not null constraint DF__T_A_Repor__fDays__3DB3258D default (1),
   fManHour             smallint             not null constraint DF__T_A_Repor__fManH__3EA749C6 default (0),
   fOverdueCount        tinyint              not null constraint DF__T_A_Repor__fOver__3F9B6DFF default (0),
   fOverdueMinutes      smallint             not null constraint DF__T_A_Repor__fOver__408F9238 default (0),
   fEarlyCount          tinyint              not null constraint DF__T_A_Repor__fEarl__4183B671 default (0),
   fEarlyMinutes        smallint             not null constraint DF__T_A_Repor__fEarl__4277DAAA default (0),
   fAbsentDays          tinyint              not null constraint DF__T_A_Repor__fAbse__436BFEE3 default (0),
   fAbsentMinutes       smallint             not null constraint DF__T_A_Repor__fAbse__4460231C default (0),
   fLeaveDays           tinyint              not null constraint DF__T_A_Repor__fLeav__45544755 default (0),
   fLeaveMinutes        smallint             not null constraint DF__T_A_Repor__fLeav__46486B8E default (0),
   fEvectionDays        tinyint              not null constraint DF__T_A_Repor__fEvec__473C8FC7 default (0),
   fEvectionMinutes     smallint             not null constraint DF__T_A_Repor__fEvec__4830B400 default (0),
   fOvertimeMinutes     smallint             not null constraint DF__T_A_Repor__fOver__4924D839 default (0),
   fExplain             varchar(1000)        collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_A_ReportMonths                                      */
/*==============================================================*/
create table dbo.T_A_ReportMonths (
   fKeyID               int                  identity(1, 1),
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS not null,
   fYear                smallint             not null constraint DF__T_A_Repor__fYear__4A18FC72 default datepart(year,getdate()),
   fMonth               tinyint              not null constraint DF__T_A_Repor__fMont__4B0D20AB default datepart(month,getdate()),
   fOughtDays           tinyint              not null constraint DF__T_A_Repor__fOugh__4C0144E4 default (0),
   fFactDays            tinyint              not null constraint DF__T_A_Repor__fFact__4CF5691D default (0),
   fOverdueCount        smallint             not null constraint DF__T_A_Repor__fOver__4DE98D56 default (0),
   fOverdueMinutes      smallint             not null constraint DF__T_A_Repor__fOver__4EDDB18F default (0),
   fEarlyCount          smallint             not null constraint DF__T_A_Repor__fEarl__4FD1D5C8 default (0),
   fEarlyMinutes        smallint             not null constraint DF__T_A_Repor__fEarl__50C5FA01 default (0),
   fAbsentDays          tinyint              not null constraint DF__T_A_Repor__fAbse__51BA1E3A default (0),
   fAbsentMinutes       smallint             not null constraint DF__T_A_Repor__fAbse__52AE4273 default (0),
   fLeaveDays           tinyint              not null constraint DF__T_A_Repor__fLeav__53A266AC default (0),
   fLeaveMinutes        smallint             not null constraint DF__T_A_Repor__fLeav__54968AE5 default (0),
   fEvectionDays        tinyint              not null constraint DF__T_A_Repor__fEvec__558AAF1E default (0),
   fEvectionMinutes     smallint             not null constraint DF__T_A_Repor__fEvec__567ED357 default (0),
   fOvertimeMinutes     smallint             not null constraint DF__T_A_Repor__fOver__5772F790 default (0),
   fManhour             int                  not null constraint DF__T_A_Repor__fManh__58671BC9 default (0)
)
on "PRIMARY"
go

alter table dbo.T_A_ReportMonths
   add constraint PK__T_A_ReportMonths primary key (fKeyID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_A_RingSet                                           */
/*==============================================================*/
create table dbo.T_A_RingSet (
   fRingCode            tinyint              not null,
   fRingTime            varchar(5)           collate Chinese_PRC_CI_AS not null constraint DF__T_A_RingS__fRing__595B4002 default '00:00',
   fRingWait            int                  not null constraint DF__T_A_RingS__fRing__5A4F643B default (0)
)
on "PRIMARY"
go

alter table dbo.T_A_RingSet
   add constraint PK__T_A_RingSet primary key (fRingCode)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_A_WTArrange                                         */
/*==============================================================*/
create table dbo.T_A_WTArrange (
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS not null,
   fYear                int                  not null,
   fMonth               int                  not null,
   fName                varchar(20)          collate Chinese_PRC_CI_AS null,
   fOughtDays           int                  null,
   fDay1                varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay2                varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay3                varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay4                varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay5                varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay6                varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay7                varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay8                varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay9                varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay10               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay11               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay12               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay13               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay14               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay15               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay16               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay17               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay18               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay19               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay20               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay21               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay22               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay23               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay24               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay25               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay26               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay27               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay28               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay29               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay30               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay31               varchar(4)           collate Chinese_PRC_CI_AS null,
   fArrangeDate         datetime             not null constraint DF__T_A_WTArr__fArra__740F363E default getdate(),
   fOperID              varchar(4)           collate Chinese_PRC_CI_AS not null,
   fRemark              varchar(100)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_A_WTArrange
   add constraint PK__T_A_WTArrange primary key (fAccountID, fYear, fMonth)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_A_WorkTime                                          */
/*==============================================================*/
create table dbo.T_A_WorkTime (
   fWorkTimeCode        varchar(4)           collate Chinese_PRC_CI_AS not null,
   fWorkTimeName        varchar(30)          collate Chinese_PRC_CI_AS not null,
   fDeptCode            varchar(10)          collate Chinese_PRC_CI_AS not null constraint DF__T_A_WorkT__fDept__5B438874 default (0),
   fOnDuty1             varchar(5)           collate Chinese_PRC_CI_AS not null,
   fOnDuty1Enable       bit                  not null constraint DF__T_A_WorkT__fOnDu__5C37ACAD default (0),
   fOffDuty1            varchar(5)           collate Chinese_PRC_CI_AS not null,
   fOffDuty1Enable      bit                  not null constraint DF__T_A_WorkT__fOffD__5D2BD0E6 default (0),
   fIsOverTime1         bit                  not null constraint DF__T_A_WorkT__fIsOv__5E1FF51F default (0),
   fOnDuty2             varchar(5)           collate Chinese_PRC_CI_AS null,
   fOnDuty2Enable       bit                  not null constraint DF__T_A_WorkT__fOnDu__5F141958 default (0),
   fOffDuty2            varchar(5)           collate Chinese_PRC_CI_AS null,
   fOffDuty2Enable      bit                  not null constraint DF__T_A_WorkT__fOffD__60083D91 default (0),
   fIsOverTime2         bit                  not null constraint DF__T_A_WorkT__fIsOv__60FC61CA default (0),
   fOnDuty3             varchar(5)           collate Chinese_PRC_CI_AS null,
   fOnDuty3Enable       bit                  not null constraint DF__T_A_WorkT__fOnDu__61F08603 default (0),
   fOffDuty3            varchar(5)           collate Chinese_PRC_CI_AS null,
   fOffDuty3Enable      bit                  not null constraint DF__T_A_WorkT__fOffD__62E4AA3C default (0),
   fIsOverTime3         bit                  not null constraint DF__T_A_WorkT__fIsOv__63D8CE75 default (0),
   fOnDuty4             varchar(5)           collate Chinese_PRC_CI_AS null,
   fOnDuty4Enable       bit                  not null constraint DF__T_A_WorkT__fOnDu__64CCF2AE default (0),
   fOffDuty4            varchar(5)           collate Chinese_PRC_CI_AS null,
   fOffDuty4Enable      bit                  not null constraint DF__T_A_WorkT__fOffD__65C116E7 default (0),
   fIsOverTime4         bit                  not null constraint DF__T_A_WorkT__fIsOv__66B53B20 default (0),
   fOnDuty5             varchar(5)           collate Chinese_PRC_CI_AS null,
   fOnDuty5Enable       bit                  not null constraint DF__T_A_WorkT__fOnDu__67A95F59 default (0),
   fOffDuty5            varchar(5)           collate Chinese_PRC_CI_AS null,
   fOffDuty5Enable      bit                  not null constraint DF__T_A_WorkT__fOffD__689D8392 default (0),
   fIsOverTime5         bit                  not null constraint DF__T_A_WorkT__fIsOv__6991A7CB default (0),
   fOnDuty6             varchar(5)           collate Chinese_PRC_CI_AS null,
   fOnDuty6Enable       bit                  not null constraint DF__T_A_WorkT__fOnDu__6A85CC04 default (0),
   fOffDuty6            varchar(5)           collate Chinese_PRC_CI_AS null,
   fOffDuty6Enable      bit                  not null constraint DF__T_A_WorkT__fOffD__6B79F03D default (0),
   fIsOverTime6         bit                  not null constraint DF__T_A_WorkT__fIsOv__6C6E1476 default (0),
   fWorkTimes           int                  not null constraint DF__T_A_WorkT__fWork__6D6238AF default (0),
   fOvertimes           int                  not null constraint DF__T_A_WorkT__fOver__6E565CE8 default (0),
   fWorkTimeCount       smallint             not null constraint DF__T_A_WorkT__fWork__6F4A8121 default (1),
   fEnable              bit                  not null constraint DF__T_A_WorkT__fEnab__703EA55A default (1),
   fIsDefault           bit                  not null constraint DF__T_A_WorkT__fIsDe__7132C993 default (0)
)
on "PRIMARY"
go

alter table dbo.T_A_WorkTime
   add constraint PK_T_A_WorkTime primary key (fWorkTimeCode)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_A_WorkTimeStyle                                     */
/*==============================================================*/
create table dbo.T_A_WorkTimeStyle (
   fWTStyleCode         varchar(4)           collate Chinese_PRC_CI_AS not null,
   fWTStyleName         varchar(30)          collate Chinese_PRC_CI_AS not null,
   fWTStyleType         smallint             not null constraint DF__T_A_WorkT__fWTSt__7226EDCC default (0),
   fWTDays              smallint             not null constraint DF__T_A_WorkT__fWTDa__731B1205 default (0),
   fDay1                varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay2                varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay3                varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay4                varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay5                varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay6                varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay7                varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay8                varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay9                varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay10               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay11               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay12               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay13               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay14               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay15               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay16               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay17               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay18               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay19               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay20               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay21               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay22               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay23               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay24               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay25               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay26               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay27               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay28               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay29               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay30               varchar(4)           collate Chinese_PRC_CI_AS null,
   fDay31               varchar(4)           collate Chinese_PRC_CI_AS null,
   fRemark              varchar(100)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_A_WorkTimeStyle
   add constraint PK__T_A_WorkTimeStyle primary key (fWTStyleCode)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_BankCardCode                                      */
/*==============================================================*/
create table dbo.T_B_BankCardCode (
   fKeyId               int                  identity(1, 1),
   fBankCode            varchar(8)           collate Chinese_PRC_CI_AS not null,
   fCardCode            varchar(6)           collate Chinese_PRC_CI_AS not null,
   fXyBz                smallint             not null,
   fRemark              varchar(100)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_BankCode                                          */
/*==============================================================*/
create table dbo.T_B_BankCode (
   fKeyId               int                  identity(1, 1),
   fBankCode            varchar(8)           collate Chinese_PRC_CI_AS not null,
   fBankName            varchar(100)         collate Chinese_PRC_CI_AS not null,
   fBankAddr            varchar(100)         collate Chinese_PRC_CI_AS not null,
   fBankPort            varchar(100)         collate Chinese_PRC_CI_AS not null,
   fDzAddr              varchar(200)         collate Chinese_PRC_CI_AS not null,
   fDzTime              datetime             not null,
   fDzbz                smallint             not null,
   fYDzbz               smallint             not null,
   fYdzTime             datetime             null,
   fXybz                smallint             not null,
   fReServe             varchar(100)         collate Chinese_PRC_CI_AS null,
   fHandDzBz            smallint             not null
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_Bzbm                                              */
/*==============================================================*/
create table dbo.T_B_Bzbm (
   fKeyID               int                  identity(1, 1),
   fBz_Id               varchar(6)           collate Chinese_PRC_CI_AS not null,
   fStation_Id          varchar(2)           collate Chinese_PRC_CI_AS not null,
   fSt_Id               varchar(4)           collate Chinese_PRC_CI_AS not null,
   fBz_Name             varchar(40)          collate Chinese_PRC_CI_AS not null,
   fTc_Bl               money         null
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_CardHis                                           */
/*==============================================================*/
create table dbo.T_B_CardHis (
   fKeyID               int                  identity(1, 1),
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS not null,
   fSerialNo            varchar(30)          collate Chinese_PRC_CI_AS null,
   fDept                varchar(50)          collate Chinese_PRC_CI_AS null,
   fBeginTime           datetime             null constraint DF__T_B_CardH__fBegi__75035A77 default getdate(),
   fEndTime             datetime             null constraint DF__T_B_CardH__fEndT__75F77EB0 default getdate(),
   fUsed                bit                  not null constraint DF__T_B_CardH__fUsed__76EBA2E9 default (1)
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_CardInfo                                          */
/*==============================================================*/
create table dbo.T_B_CardInfo (
   fKeyID               int                  identity(1, 1),
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS null,
   fPhysicalNo          varchar(30)          collate Chinese_PRC_CI_AS null,
   fKKDateTime          datetime             null,
   fXKDateTime          datetime             null,
   fCard_State          int                  null,
   fCardType            int                  null,
   fOperID              int                  null,
   fRemark              varchar(100)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_B_CardInfo
   add constraint PK__T_B_Card__23D5CF66628FA481 primary key (fKeyID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_CardPc                                            */
/*==============================================================*/
create table dbo.T_B_CardPc (
   fCardPc_Id           smallint             not null,
   fCardPc_Name         varchar(20)          collate Chinese_PRC_CI_AS not null,
   fUse_BeginTime       datetime             not null,
   fUse_EndTime         datetime             not null,
   fState               smallint             null
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_CardType                                          */
/*==============================================================*/
create table dbo.T_B_CardType (
   fCardTypeID          int                  not null,
   fCardTypeName        varchar(40)          collate Chinese_PRC_CI_AS not null,
   fIsMainCard          bit                  not null,
   fCardType            int                  not null,
   fFirstPurseID        int                  not null constraint DF__T_B_CardT__fFirs__118A8A8C default (0),
   fSecondPurseID       int                  not null constraint DF__T_B_CardT__fSeco__127EAEC5 default (0),
   fState               bit                  not null constraint DF__T_B_CardT__fStat__1372D2FE default (0),
   fDeposit             money                not null constraint DF__T_B_CardT__fDepo__1466F737 default (0)
)
on "PRIMARY"
go

alter table dbo.T_B_CardType
   add constraint PK_T_B_CardType primary key (fCardTypeID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_Cards                                             */
/*==============================================================*/
create table dbo.T_B_Cards (
   fAccountID           varchar(8)           collate Chinese_PRC_CI_AS not null,
   fCardTypeID          int                  not null,
   fSerialID            varchar(16)          collate Chinese_PRC_CI_AS not null,
   fSerialNo            varchar(16)          collate Chinese_PRC_CI_AS null,
   fCardTransNo         int                  not null,
   fCardState           int                  not null,
   fCardBatchID         int                  not null constraint DF_T_B_Cards_fCardBatchID default (0),
   fCreateDate          datetime             not null constraint DF__T_B_Cards__fCrea__1837881B default getdate(),
   fLimitDate           datetime             not null,
   fDeleteDate          datetime             null,
   fCardDeposit         money                not null constraint DF__T_B_Cards__fDepo__192BAC54 default (0)
)
on "PRIMARY"
go

alter table dbo.T_B_Cards
   add constraint PK_T_B_Cards primary key (fAccountID, fCardTypeID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_DbShinkHistory                                    */
/*==============================================================*/
create table dbo.T_B_DbShinkHistory (
   fKeyID               int                  identity(1, 1),
   fOperDate            datetime             null,
   fStationID           varchar(2)           collate Chinese_PRC_CI_AS null,
   fOperID              int                  null
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_DelEmployee                                       */
/*==============================================================*/
create table dbo.T_B_DelEmployee (
   fAccountId           varchar(8)           collate Chinese_PRC_CI_AS not null,
   fCardNo              varchar(12)          collate Chinese_PRC_CI_AS not null,
   fName                varchar(20)          collate Chinese_PRC_CI_AS null,
   fDept                varchar(15)          collate Chinese_PRC_CI_AS null,
   fL_Money             money         null constraint DF__T_B_DelEm__fL_Mo__7E8CC4B1 default (0),
   fKh_Money            money         null constraint DF__T_B_DelEm__fKh_M__7F80E8EA default (0),
   fCh_Charge           money         null constraint DF__T_B_DelEm__fCh_C__00750D23 default (0),
   fBack_Money          money         null constraint DF__T_B_DelEm__fBack__0169315C default (0),
   fDel_date            datetime             not null,
   fUsed                tinyint              not null,
   fKh_date             datetime             not null
)
on "PRIMARY"
go

alter table dbo.T_B_DelEmployee
   add constraint PK__T_B_DelEmployee primary key (fAccountId)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_Dept                                              */
/*==============================================================*/
create table dbo.T_B_Dept (
   fDeptCode            varchar(20)          collate Chinese_PRC_CI_AS not null,
   fDeptName            varchar(50)          collate Chinese_PRC_CI_AS not null,
   fDeptLevel           tinyint              not null,
   fDeptID              int                  not null,
   fRemark              varchar(100)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_B_Dept
   add constraint PK_T_B_Dept primary key (fDeptID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_Diploma                                           */
/*==============================================================*/
create table dbo.T_B_Diploma (
   fDiplomaCode         varchar(2)           collate Chinese_PRC_CI_AS not null,
   fDiplomaName         varchar(10)          collate Chinese_PRC_CI_AS not null
)
on "PRIMARY"
go

alter table dbo.T_B_Diploma
   add constraint PK_T_B_Diploma primary key (fDiplomaCode)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_Dish                                              */
/*==============================================================*/
create table dbo.T_B_Dish (
   fKeyID               int                  identity(1, 1),
   fDishID              int                  not null,
   fDishName            varchar(50)          collate Chinese_PRC_CI_AS null,
   fDishUnit            varchar(50)          collate Chinese_PRC_CI_AS null,
   fDishPrice           money         null,
   fRemark              varchar(200)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_B_Dish
   add constraint PK_T_B_Dish primary key (fKeyID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_EmpFace                                           */
/*==============================================================*/
create table dbo.T_B_EmpFace (
   fACcountid           varchar(18)          collate Chinese_PRC_CI_AS not null,
   fEmpFace             varchar(Max)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_EmpFinger                                         */
/*==============================================================*/
create table dbo.T_B_EmpFinger (
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS not null,
   fFingerList          varchar(10)          collate Chinese_PRC_CI_AS not null,
   fFinger0             image                null,
   fFinger1             image                null,
   fFinger2             image                null,
   fFinger3             image                null,
   fFinger4             image                null,
   fFinger5             image                null,
   fFinger6             image                null,
   fFinger7             image                null,
   fFinger8             image                null,
   fFinger9             image                null
)
on "PRIMARY"
go

alter table dbo.T_B_EmpFinger
   add constraint PK_T_B_EmpFinger primary key (fAccountID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_Employee                                          */
/*==============================================================*/
create table dbo.T_B_Employee (
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS not null,
   fEmployeeCode        varchar(20)          collate Chinese_PRC_CI_AS not null,
   fSerialNo            varchar(30)          collate Chinese_PRC_CI_AS null,
   fCardID              varchar(20)          collate Chinese_PRC_CI_AS null,
   fName                varchar(20)          collate Chinese_PRC_CI_AS not null,
   fIDCard              varchar(18)          collate Chinese_PRC_CI_AS null,
   fSex                 bit                  not null,
   fBirthday            datetime             null,
   fNation              varchar(2)           collate Chinese_PRC_CI_AS null,
   fNativePlace         varchar(2)           collate Chinese_PRC_CI_AS null,
   fGroup               int                  null,
   fDept                varchar(50)          collate Chinese_PRC_CI_AS not null,
   fRoomID              varchar(10)          collate Chinese_PRC_CI_AS null,
   fJob                 varchar(50)          collate Chinese_PRC_CI_AS null,
   fPhoto               image                null,
   fChecked             bit                  not null,
   fCheckSystem         varchar(4)           collate Chinese_PRC_CI_AS null,
   fDiploma             varchar(2)           collate Chinese_PRC_CI_AS null,
   fGraduateDate        datetime             null,
   fSchool              varchar(30)          collate Chinese_PRC_CI_AS null,
   fSpecialty           varchar(20)          collate Chinese_PRC_CI_AS null,
   fAddress             varchar(60)          collate Chinese_PRC_CI_AS null,
   fPhoneCode           varchar(20)          collate Chinese_PRC_CI_AS null,
   fMobilePhoneCode     varchar(15)          collate Chinese_PRC_CI_AS null,
   fEmail               varchar(30)          collate Chinese_PRC_CI_AS null,
   fEnterDate           datetime             not null,
   fCheckDate           datetime             null,
   fState               smallint             not null,
   fResume              varchar(500)         collate Chinese_PRC_CI_AS null,
   fRemark              varchar(200)         collate Chinese_PRC_CI_AS null,
   fCard_State          varchar(1)           collate Chinese_PRC_CI_AS not null,
   fPassword            varchar(10)          collate Chinese_PRC_CI_AS null,
   fCard_TypeId         smallint             null,
   fPass_True           bit                  not null,
   fId_TypeId           smallint             null,
   fKh_Date             datetime             null,
   fKh_Money            money         null,
   fKh_JE               money         null,
   fKh_Charge           money         null,
   fBalanceMon          money         null constraint DF__T_B_Emplo__fBala__48CFD27E default (0.00),
   fBalanceSub          money         null constraint DF__T_B_Emplo__fBala__49C3F6B7 default (0.00),
   fCountMon            int                  null constraint DF__T_B_Emplo__fCoun__4AB81AF0 default (0),
   fCountSub            int                  null constraint DF__T_B_Emplo__fCoun__4BAC3F29 default (0),
   fXgEnable            bit                  null,
   fEgsPass             varchar(6)           collate Chinese_PRC_CI_AS null,
   fCardValidDate       varchar(20)          collate Chinese_PRC_CI_AS not null constraint DF__T_B_Emplo__fCard__4CA06362 default '',
   fIsBind              int                  not null constraint DF__T_B_Emplo__fIsBi__4D94879B default (0),
   fBankNo              varchar(40)          collate Chinese_PRC_CI_AS null,
   fParentName          varchar(40)          collate Chinese_PRC_CI_AS null,
   fLastOperateTime     datetime             null,
   fHaveKhWater         int                  not null constraint DF__T_B_Emplo__fHave__4E88ABD4 default (0),
   rver                 timestamp            not null
)
on "PRIMARY"
go

alter table dbo.T_B_Employee
   add constraint PK_T_B_Employee primary key (fAccountID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_EvectionRec                                       */
/*==============================================================*/
create table dbo.T_B_EvectionRec (
   fKeyID               int                  identity(1, 1),
   fNoteCode            varchar(18)          collate Chinese_PRC_CI_AS null,
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS not null,
   fDestination         varchar(4)           collate Chinese_PRC_CI_AS not null constraint DF__T_B_Evect__fDest__025D5595 default (0),
   fTimeBegin           datetime             not null,
   fTimeEnd             datetime             not null,
   fAllDay              bit                  not null constraint DF__T_B_Evect__fAllD__035179CE default (0),
   fApprover            varchar(8)           collate Chinese_PRC_CI_AS null,
   fDays                tinyint              null constraint DF__T_B_Evect__fDays__04459E07 default (0),
   fMinutes             smallint             null constraint DF__T_B_Evect__fMinu__0539C240 default (0),
   fEvectionReason      varchar(100)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_B_EvectionRec
   add constraint PK__T_B_EvectionRec primary key (fKeyID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_EvectionReclist                                   */
/*==============================================================*/
create table dbo.T_B_EvectionReclist (
   ID                   int                  identity(1, 1),
   fKeyID               int                  null,
   fNoteCode            varchar(18)          collate Chinese_PRC_CI_AS not null,
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS null,
   fDestination         varchar(4)           collate Chinese_PRC_CI_AS null,
   fTimeBegin           datetime             null,
   fTimeEnd             datetime             null,
   fAllDay              bit                  null,
   fApprover            varchar(8)           collate Chinese_PRC_CI_AS null,
   fDays                tinyint              not null,
   fMinutes             smallint             null,
   fEvectionReason      varchar(100)         collate Chinese_PRC_CI_AS not null
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_Holiday                                           */
/*==============================================================*/
create table dbo.T_B_Holiday (
   fHolidayCode         varchar(8)           collate Chinese_PRC_CI_AS not null,
   fHolidayName         varchar(20)          collate Chinese_PRC_CI_AS not null,
   fHolidayDate         varchar(5)           collate Chinese_PRC_CI_AS not null,
   fHolidayEnd          varchar(5)           collate Chinese_PRC_CI_AS not null,
   fHolidays            smallint             not null constraint DF__T_B_Holid__fHoli__062DE679 default (1)
)
on "PRIMARY"
go

alter table dbo.T_B_Holiday
   add constraint PK_T_B_Holiday primary key (fHolidayCode)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_Job                                               */
/*==============================================================*/
create table dbo.T_B_Job (
   fJobCode             varchar(2)           collate Chinese_PRC_CI_AS not null,
   fJobName             varchar(10)          collate Chinese_PRC_CI_AS not null
)
on "PRIMARY"
go

alter table dbo.T_B_Job
   add constraint PK_T_B_Job primary key (fJobCode)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_Keys                                              */
/*==============================================================*/
create table dbo.T_B_Keys (
   fPswType             int                  not null,
   fPassword            varchar(100)         collate Chinese_PRC_CI_AS not null
)
on "PRIMARY"
go

alter table dbo.T_B_Keys
   add constraint PK_T_B_Keys primary key (fPswType)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_Leave                                             */
/*==============================================================*/
create table dbo.T_B_Leave (
   fLeaveCode           varchar(2)           collate Chinese_PRC_CI_AS not null,
   fLeaveName           varchar(10)          collate Chinese_PRC_CI_AS not null
)
on "PRIMARY"
go

alter table dbo.T_B_Leave
   add constraint PK__T_B_Leave primary key (fLeaveCode)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_LeaveRec                                          */
/*==============================================================*/
create table dbo.T_B_LeaveRec (
   fKeyID               int                  identity(1, 1),
   fNoteCode            varchar(18)          collate Chinese_PRC_CI_AS null,
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS not null,
   fLeaveType           varchar(4)           collate Chinese_PRC_CI_AS not null constraint DF__T_B_Leave__fLeav__07220AB2 default (0),
   fTimeBegin           datetime             not null,
   fTimeEnd             datetime             not null,
   fAllDay              bit                  not null constraint DF__T_B_Leave__fAllD__08162EEB default (0),
   fApprover            varchar(8)           collate Chinese_PRC_CI_AS null,
   fDays                tinyint              null constraint DF__T_B_Leave__fDays__090A5324 default (0),
   fMinutes             smallint             null constraint DF__T_B_Leave__fMinu__09FE775D default (0),
   fLeaveReason         varchar(100)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_B_LeaveRec
   add constraint PK__T_B_LeaveRec primary key (fKeyID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_LeaveRecList                                      */
/*==============================================================*/
create table dbo.T_B_LeaveRecList (
   KeyID                int                  identity(1, 1),
   fkeyID               varchar(18)          collate Chinese_PRC_CI_AS null,
   fNoteCode            varchar(18)          collate Chinese_PRC_CI_AS null,
   fleavetype           varchar(4)           collate Chinese_PRC_CI_AS null,
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS null,
   fTimeBegin           datetime             null,
   fTimeEnd             datetime             null,
   fAllday              bit                  null,
   fApprover            varchar(8)           collate Chinese_PRC_CI_AS null,
   fDays                tinyint              null,
   fMinutes             smallint             null,
   fLeaveReason         varchar(100)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_ListDown                                          */
/*==============================================================*/
create table dbo.T_B_ListDown (
   fID                  int                  identity(1, 1),
   fType                varchar(2)           collate Chinese_PRC_CI_AS not null,
   fPosID               int                  not null,
   fVer                 int                  not null,
   fTime                datetime             not null constraint DF__T_B_ListD__fTime__0AF29B96 default (0),
   fDesc                varchar(20)          collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_B_ListDown
   add constraint PK_T_B_ListDown primary key (fID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_ListDownHis                                       */
/*==============================================================*/
create table dbo.T_B_ListDownHis (
   fID                  int                  not null,
   fType                varchar(2)           collate Chinese_PRC_CI_AS not null,
   fPosID               int                  not null,
   fVer                 int                  not null,
   fTime                datetime             not null constraint DF__T_B_ListD__fTime__0BE6BFCF default (0),
   fDesc                varchar(20)          collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_B_ListDownHis
   add constraint PK_T_B_ListDownHis primary key (fID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_ManType                                           */
/*==============================================================*/
create table dbo.T_B_ManType (
   fId_TypeId           smallint             not null,
   fId_TypeName         varchar(20)          collate Chinese_PRC_CI_AS not null,
   fKh_Money            money         not null,
   fKh_Charge           money         not null,
   fCh_Charge           money         not null,
   fHk_Charge           money         not null,
   fBk_Charge           money         not null,
   fBk_Money            money         not null,
   fGs_Charge           money         not null,
   fJg_Charge           money         not null,
   fUes_PassMoney       money         not null,
   fManage_Charge       money         not null,
   fsubsity_money       money         not null,
   fcons_Group          varchar(50)          collate Chinese_PRC_CI_AS null,
   fparent              int                  null,
   fLimitSingle         money                null constraint DF__T_B_ManTy__fLimi__0FB750B3 default (0),
   fLimitDay            money                null constraint DF__T_B_ManTy__fLimi__10AB74EC default (0)
)
on "PRIMARY"
go

alter table dbo.T_B_ManType
   add constraint PK_T_B_ManType primary key (fId_TypeId)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_ManTypeDiscount                                   */
/*==============================================================*/
create table dbo.T_B_ManTypeDiscount (
   fID                  int                  identity(1, 1),
   fUserTypeID          smallint             not null,
   fMealID              varchar(9)           collate Chinese_PRC_CI_AS not null,
   FFirstDiscount       money                null constraint DF__T_B_ManTy__FFirs__119F9925 default (0)
)
on "PRIMARY"
go

alter table dbo.T_B_ManTypeDiscount
   add constraint PK_T_B_ManTypeDiscount primary key (fID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_Manager                                           */
/*==============================================================*/
create table dbo.T_B_Manager (
   fOperID              int                  identity(1, 1),
   fOperName            varchar(40)          collate Chinese_PRC_CI_AS not null,
   fLoginName           varchar(40)          collate Chinese_PRC_CI_AS not null,
   fOperPass            varchar(40)          collate Chinese_PRC_CI_AS null,
   fDeptCode            varchar(200)         collate Chinese_PRC_CI_AS null,
   fStationId           varchar(2)           collate Chinese_PRC_CI_AS null,
   fUsefulLife          datetime             null,
   fPermanent           bit                  not null constraint DF__T_B_Manag__fPerm__0CDAE408 default (0),
   fLocked              bit                  not null constraint DF__T_B_Manag__fLock__0DCF0841 default (0),
   fIsManager           bit                  not null constraint DF__T_B_Manag__fIsMa__0EC32C7A default (0),
   fCardNo              varchar(30)          collate Chinese_PRC_CI_AS null,
   fCardPass            varchar(8)           collate Chinese_PRC_CI_AS null,
   fDesc                varchar(100)         collate Chinese_PRC_CI_AS null,
   fReportRight         varchar(200)         collate Chinese_PRC_CI_AS null,
   fRight               image                null
)
on "PRIMARY"
go

alter table dbo.T_B_Manager
   add constraint PK__T_B_Manager primary key (fOperID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_ManagerCard                                       */
/*==============================================================*/
create table dbo.T_B_ManagerCard (
   fID                  int                  identity(1, 1),
   fOperID              int                  not null,
   fCardNo              varchar(30)          collate Chinese_PRC_CI_AS null,
   fCardPass            varchar(8)           collate Chinese_PRC_CI_AS null,
   fIsUsed              bit                  not null,
   fDesc                varchar(100)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_B_ManagerCard
   add constraint PK_T_B_ManagerCard primary key (fID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_MealCp                                            */
/*==============================================================*/
create table dbo.T_B_MealCp (
   fID                  int                  identity(1, 1),
   fMealId              varchar(3)           collate Chinese_PRC_CI_AS not null,
   fLableCode           int                  not null constraint DF__T_B_MealC__fLabl__1293BD5E default (0),
   fPrice               money         not null constraint DF__T_B_MealC__fPric__1387E197 default (0)
)
on "PRIMARY"
go

alter table dbo.T_B_MealCp
   add constraint PK__T_B_Meal__D9F8259C0E240DFC primary key (fID)
      on "PRIMARY"
go

alter table dbo.T_B_MealCp
   add constraint UQ__T_B_Meal__AEC5808D11007AA7 unique (fMealId, fLableCode)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_MealLimit                                         */
/*==============================================================*/
create table dbo.T_B_MealLimit (
   fID                  int                  not null,
   fId_TypeId           smallint             not null,
   Meal1Limit           int                  not null constraint DF__T_B_MealL__Meal1__147C05D0 default (0),
   Meal2Limit           int                  not null constraint DF__T_B_MealL__Meal2__15702A09 default (0),
   Meal3Limit           int                  not null constraint DF__T_B_MealL__Meal3__16644E42 default (0),
   Meal4Limit           int                  not null constraint DF__T_B_MealL__Meal4__1758727B default (0),
   Meal5Limit           int                  not null constraint DF__T_B_MealL__Meal5__184C96B4 default (0),
   Meal6Limit           int                  not null constraint DF__T_B_MealL__Meal6__1940BAED default (0)
)
on "PRIMARY"
go

alter table dbo.T_B_MealLimit
   add constraint PK_T_B_MealLimit primary key (fID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_MealSet                                           */
/*==============================================================*/
create table dbo.T_B_MealSet (
   fMeal_Id             varchar(3)           collate Chinese_PRC_CI_AS not null,
   fMeal_Name           varchar(20)          collate Chinese_PRC_CI_AS not null,
   fBegin_Time          datetime             not null,
   fEnd_Time            datetime             not null,
   fLimitBc             int                  null constraint DF__T_B_MealS__fLimi__1A34DF26 default (0)
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_MealTradeLimit                                    */
/*==============================================================*/
create table dbo.T_B_MealTradeLimit (
   fID                  int                  identity(1, 1),
   fMealID              varchar(50)          collate Chinese_PRC_CI_AS null,
   fPosId               int                  null,
   fTradeType           int                  null,
   fTradeCount          int                  null,
   fTradeMoney          money         null
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_Nation                                            */
/*==============================================================*/
create table dbo.T_B_Nation (
   fNationCode          varchar(2)           collate Chinese_PRC_CI_AS not null,
   fNationName          varchar(10)          collate Chinese_PRC_CI_AS not null
)
on "PRIMARY"
go

alter table dbo.T_B_Nation
   add constraint PK_T_B_Nation primary key (fNationCode)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_NoDiscountList                                    */
/*==============================================================*/
create table dbo.T_B_NoDiscountList (
   fKeyID               int                  identity(1, 1),
   fPosID               int                  not null
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_OperateObject                                     */
/*==============================================================*/
create table dbo.T_B_OperateObject (
   fOperType            int                  null,
   fAccountID           varchar(10)          collate Chinese_PRC_CI_AS null,
   fSerialNo            varchar(10)          collate Chinese_PRC_CI_AS null,
   fPurseCode           int                  null,
   fCreateTime          datetime             null,
   fRemark              varchar(100)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_Operator                                          */
/*==============================================================*/
create table dbo.T_B_Operator (
   fOperID              int                  identity(1, 1),
   fLoginName           varchar(40)          collate Chinese_PRC_CI_AS not null,
   fOperName            varchar(40)          collate Chinese_PRC_CI_AS not null,
   fOperPass            varchar(40)          collate Chinese_PRC_CI_AS null,
   fDeptCode            varchar(20)          collate Chinese_PRC_CI_AS null,
   fStationId           varchar(2)           collate Chinese_PRC_CI_AS null,
   fUsefulLife          datetime             null,
   fPermanent           bit                  not null,
   fLocked              bit                  not null,
   fSysManager          bit                  not null,
   fCardNo              varchar(8)           collate Chinese_PRC_CI_AS null,
   fCardPass            varchar(4)           collate Chinese_PRC_CI_AS null,
   fDesc                varchar(100)         collate Chinese_PRC_CI_AS null,
   fReportRight         varchar(400)         collate Chinese_PRC_CI_AS null,
   fRight               image                null
)
on "PRIMARY"
go

alter table dbo.T_B_Operator
   add constraint PK_T_B_Operator primary key (fOperID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_OvertimeRec                                       */
/*==============================================================*/
create table dbo.T_B_OvertimeRec (
   fKeyID               int                  identity(1, 1),
   fNoteCode            varchar(18)          collate Chinese_PRC_CI_AS null,
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS not null,
   fTimeBegin           datetime             not null,
   fTimeEnd             datetime             not null,
   fMinutes             smallint             not null,
   fOverTimeReason      varchar(100)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_B_OvertimeRec
   add constraint PK__T_B_OvertimeRec primary key (fKeyID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_Photos                                            */
/*==============================================================*/
create table dbo.T_B_Photos (
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS not null,
   fPhoto               image                null
)
on "PRIMARY"
go

alter table dbo.T_B_Photos
   add constraint PK_T_C_Photo primary key (fAccountID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_Plans                                             */
/*==============================================================*/
create table dbo.T_B_Plans (
   fPlanID              int                  identity(1, 1),
   fPlanName            varchar(60)          collate Chinese_PRC_CI_AS null,
   fPlanType            int                  not null constraint DF__T_B_Plans__fPlan__1B29035F default (0),
   fPlanTimeType        int                  not null constraint DF__T_B_Plans__fPlan__1C1D2798 default (0),
   fPlanTime            varchar(50)          collate Chinese_PRC_CI_AS not null,
   fCreateTime          datetime             not null constraint DF__T_B_Plans__fCrea__1D114BD1 default getdate(),
   fEndTime             datetime             not null,
   fStartTime           datetime             not null constraint DF__T_B_Plans__fStar__1E05700A default getdate(),
   fStopTime            datetime             not null,
   fOperID              int                  not null,
   fState               int                  not null constraint DF__T_B_Plans__fStat__1EF99443 default (0),
   fStationID           varchar(2)           collate Chinese_PRC_CI_AS not null constraint DF__T_B_Plans__fStat__1FEDB87C default '01',
   fRemark              varchar(200)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_B_Plans
   add constraint PK_T_B_Plans primary key (fPlanID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_Pos                                               */
/*==============================================================*/
create table dbo.T_B_Pos (
   fPosID               int                  not null,
   fPosName             varchar(40)          collate Chinese_PRC_CI_AS not null,
   fPosType             tinyint              not null,
   fPosClass            tinyint              not null,
   fPosPwd              varchar(4)           collate Chinese_PRC_CI_AS null,
   fCom                 smallint             not null,
   fConnType            tinyint              not null,
   fState               bit                  not null,
   fSiteID              varchar(6)           collate Chinese_PRC_CI_AS null,
   fIpAddr              varchar(15)          collate Chinese_PRC_CI_AS null,
   fTcpPort             int                  null,
   fServerIp            varchar(15)          collate Chinese_PRC_CI_AS null,
   fIssuer              bit                  not null,
   fPosVersion          varchar(10)          collate Chinese_PRC_CI_AS null,
   fMJType              int                  not null,
   fDoorLock            int                  not null,
   fWarnTime            int                  null,
   fFireAlarmTime       int                  null,
   fHintTime            int                  null,
   fWarnExport          tinyint              null,
   fFireWarnExport      tinyint              null,
   fSuperPsd            varchar(6)           collate Chinese_PRC_CI_AS null,
   fBasePsd             varchar(6)           collate Chinese_PRC_CI_AS null,
   fIntimidatePwd       varchar(6)           collate Chinese_PRC_CI_AS null,
   fFireWarnOpen        tinyint              null,
   fWarnOpen            tinyint              null,
   fRecDisposal         tinyint              null,
   fSN                  varchar(30)          collate Chinese_PRC_CI_AS null,
   fIpMask              varchar(15)          collate Chinese_PRC_CI_AS null,
   fGetWay              varchar(15)          collate Chinese_PRC_CI_AS null,
   fServerMac           varchar(17)          collate Chinese_PRC_CI_AS null,
   fGetWayMac           varchar(17)          collate Chinese_PRC_CI_AS null,
   fPosMac              varchar(17)          collate Chinese_PRC_CI_AS null,
   fConsGroup           varchar(30)          collate Chinese_PRC_CI_AS null,
   fRate                int                  null,
   fTimeUnit            int                  null,
   fCtrlPosID           int                  null,
   fLimitCounts         tinyint              null,
   fWVer                int                  null constraint DF__T_B_Pos__fWVer__023D5A04 default (0),
   fBVer                int                  null constraint DF__T_B_Pos__fBVer__03317E3D default (0),
   fLastRecTime         datetime             null constraint DF__T_B_Pos__fLastRe__0425A276 default (0),
   fRecSerialNo         int                  null constraint DF__T_B_Pos__fRecSer__0519C6AF default (0),
   fLimitMoneyEnabled   bit                  not null constraint DF__T_B_Pos__fLimitM__060DEAE8 default (1),
   fLimitCountEnabled   bit                  not null constraint DF__T_B_Pos__fLimitC__07020F21 default (1),
   fDiscountEnabled     bit                  not null constraint DF__T_B_Pos__fDiscou__07F6335A default (1),
   fFirstPurseID        int                  null constraint DF__T_B_Pos__fFirstP__08EA5793 default (0),
   fSecondPurseID       int                  null constraint DF__T_B_Pos__fSecond__09DE7BCC default (0),
   fTransPayPos         int                  not null constraint DF__T_B_Pos__fTransP__0AD2A005 default (0)
)
on "PRIMARY"
go

alter table dbo.T_B_Pos
   add constraint PK_T_B_Pos primary key (fPosID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_PosDayRecs                                        */
/*==============================================================*/
create table dbo.T_B_PosDayRecs (
   fKeyID               varchar(20)          collate Chinese_PRC_CI_AS not null,
   fPosID               int                  not null,
   fRecDate             datetime             not null constraint DF__T_B_PosDa__fRecD__42ECDBF6 default CONVERT([varchar](10),getdate(),(120)),
   fRecCount            int                  not null constraint DF__T_B_PosDa__fRecC__43E1002F default (0),
   fErrCount            int                  not null constraint DF__T_B_PosDa__fErrC__44D52468 default (0),
   fWarnCount           int                  not null constraint DF__T_B_PosDa__fWarn__45C948A1 default (0),
   fConsSum             money                not null constraint DF__T_B_PosDa__fCons__46BD6CDA default (0),
   fSaveCount           int                  not null constraint DF__T_B_PosDa__fSave__47B19113 default (0),
   fSaveSum             money                not null constraint DF__T_B_PosDa__fSave__48A5B54C default (0),
   fTakeCount           int                  not null constraint DF__T_B_PosDa__fTake__4999D985 default (0),
   fTakeSum             money                not null constraint DF__T_B_PosDa__fTake__4A8DFDBE default (0),
   fLastRecTime         datetime             null constraint DF__T_B_PosDa__fLast__4B8221F7 default CONVERT([varchar](10),getdate(),(120)),
   fPutRightCount       int                  null constraint DF__T_B_PosDa__fPutR__4C764630 default (0),
   fPutRightSum         money                null constraint DF__T_B_PosDa__fPutR__4D6A6A69 default (0)
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_PosDish                                           */
/*==============================================================*/
create table dbo.T_B_PosDish (
   fPosID               varchar(5)           collate Chinese_PRC_CI_AS not null,
   fKeyCode             int                  not null,
   fDishID              int                  not null
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_PosType                                           */
/*==============================================================*/
create table dbo.T_B_PosType (
   fPosType             int                  not null,
   fPosTypeName         varchar(50)          collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_B_PosType
   add constraint PK_T_B_POSTYPE primary key (fPosType)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_Province                                          */
/*==============================================================*/
create table dbo.T_B_Province (
   fProvinceCode        varchar(10)          collate Chinese_PRC_CI_AS not null,
   fProvinceName        varchar(50)          collate Chinese_PRC_CI_AS not null
)
on "PRIMARY"
go

alter table dbo.T_B_Province
   add constraint PK_T_B_Province primary key (fProvinceCode)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_PurseCode                                         */
/*==============================================================*/
create table dbo.T_B_PurseCode (
   fPurseCode           int                  not null,
   fPurseName           varchar(40)          collate Chinese_PRC_CI_AS null,
   fPurseType           int                  not null,
   fRechargeType        int                  not null constraint DF__T_B_Purse__fRech__2C538F61 default (0),
   fOnLine              bit                  not null constraint DF__T_B_Purse__fOnLi__2D47B39A default (1),
   fState               int                  not null constraint DF__T_B_Purse__fStat__2E3BD7D3 default (0),
   fLimitEnabled        bit                  not null constraint DF__T_B_Purse__fLimi__2F2FFC0C default (0),
   fBottomLine          money                not null constraint DF_T_B_PurseCode_fBottomLine default (0),
   fIsMain              bit                  not null constraint DF_T_B_PurseCode_fIsMain default (0),
   fM1Addr              tinyint              null constraint DF_T_B_PurseCode_fM1Addr default (12),
   fDayLimitMoney       money          not null constraint DF__T_B_Purse__fDayL__33008CF0 default (0),
   fUpperLimitMoney     money          not null constraint DF__T_B_Purse__fUppe__51300E55 default (99999)
)
on "PRIMARY"
go

alter table dbo.T_B_PurseCode
   add constraint PK_T_B_PurseCode primary key (fPurseCode)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_Purses                                            */
/*==============================================================*/
create table dbo.T_B_Purses (
   fPurseID             varchar(10)          collate Chinese_PRC_CI_AS not null,
   fPurseCode           int                  not null,
   fAccountID           varchar(8)           collate Chinese_PRC_CI_AS not null,
   fCreateDate          datetime             not null constraint DF__T_B_Purse__fCrea__005FFE8A default getdate(),
   fLimitDate           datetime             not null,
   fEnabled             bit                  not null constraint DF_T_B_Purses_fEnabled default (0),
   fBalance             money                not null constraint DF__T_B_Purse__fBala__015422C3 default (0),
   fTransNo             int                  not null constraint DF__T_B_Purse__fTran__024846FC default (0)
)
on "PRIMARY"
go

alter table dbo.T_B_Purses
   add constraint PK_T_B_Purses primary key (fPurseID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_Station                                           */
/*==============================================================*/
create table dbo.T_B_Station (
   fKeyID               int                  identity(1, 1),
   fStation_Id          varchar(2)           collate Chinese_PRC_CI_AS not null,
   fStation_Name        varchar(20)          collate Chinese_PRC_CI_AS not null,
   fIp_Addr             varchar(15)          collate Chinese_PRC_CI_AS not null,
   fStation_Type        tinyint              not null
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_Stbm                                              */
/*==============================================================*/
create table dbo.T_B_Stbm (
   fKeyID               int                  identity(1, 1),
   fSt_Id               varchar(4)           collate Chinese_PRC_CI_AS not null,
   fStation_Id          varchar(2)           collate Chinese_PRC_CI_AS not null,
   fSt_Name             varchar(40)          collate Chinese_PRC_CI_AS not null
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_SysParam                                          */
/*==============================================================*/
create table dbo.T_B_SysParam (
   fParamName           varchar(30)          collate Chinese_PRC_CI_AS not null,
   fParamValue          varchar(1500)        collate Chinese_PRC_CI_AS null,
   fParamType           varchar(10)          collate Chinese_PRC_CI_AS not null,
   fRestrict            varchar(100)         collate Chinese_PRC_CI_AS null,
   fExplain             varchar(100)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_B_SysParam
   add constraint PK_T_B_SysParam primary key (fParamName)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_TaskErrors                                        */
/*==============================================================*/
create table dbo.T_B_TaskErrors (
   fKeyID               int                  identity(1, 1),
   fTaskID              int                  not null,
   fAccountID           varchar(8)           collate Chinese_PRC_CI_AS not null,
   fContent             varchar(200)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_B_TaskErrors
   add constraint PK_T_B_TaskErrors primary key (fKeyID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_Tasks                                             */
/*==============================================================*/
create table dbo.T_B_Tasks (
   fTaskID              int                  identity(1, 1),
   fPlanID              int                  not null,
   fTaskTime            datetime             not null constraint DF__T_B_Tasks__fTask__5C8CB268 default (0),
   fExecTime            datetime             null constraint DF__T_B_Tasks__fExec__5D80D6A1 default (0),
   fState               int                  not null constraint DF__T_B_Tasks__fStat__5E74FADA default (0),
   fSuccessCount        int                  not null constraint DF__T_B_Tasks__fSucc__5F691F13 default (0),
   fErrorCount          int                  not null constraint DF__T_B_Tasks__fErro__605D434C default (0),
   fRemark              varchar(200)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_B_Tasks
   add constraint PK_T_B_Tasks primary key (fTaskID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_UserType                                          */
/*==============================================================*/
create table dbo.T_B_UserType (
   fId_TypeID           smallint             not null,
   fId_TypeName         varchar(20)          collate Chinese_PRC_CI_AS not null,
   fKh_Money            money         not null constraint DF__T_B_UserT__fKh_M__3AA1AEB8 default (0),
   fKh_Charge           money         not null constraint DF__T_B_UserT__fKh_C__3B95D2F1 default (0),
   fCh_Charge           money         not null constraint DF__T_B_UserT__fCh_C__3C89F72A default (0),
   fHk_Charge           money         not null constraint DF__T_B_UserT__fHk_C__3D7E1B63 default (0),
   fBk_Charge           money         not null constraint DF__T_B_UserT__fBk_C__3E723F9C default (0),
   fBk_Money            money         not null constraint DF__T_B_UserT__fBk_M__3F6663D5 default (0),
   fGs_Charge           money         not null constraint DF__T_B_UserT__fGs_C__405A880E default (0),
   fJg_Charge           money         not null constraint DF__T_B_UserT__fJg_C__414EAC47 default (0),
   fUes_PassMoney       money         not null constraint DF__T_B_UserT__fUes___4242D080 default (0),
   fManage_Charge       money         not null constraint DF__T_B_UserT__fMana__4336F4B9 default (0),
   fsubsity_money       money         not null constraint DF__T_B_UserT__fsubs__442B18F2 default (0),
   fcons_Group          varchar(50)          collate Chinese_PRC_CI_AS null constraint DF__T_B_UserT__fcons__451F3D2B default '1',
   fparent              int                  null constraint DF__T_B_UserT__fpare__46136164 default (0)
)
on "PRIMARY"
go

alter table dbo.T_B_UserType
   add constraint PK_T_B_UserType primary key (fId_TypeID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_UserTypeDayLimit                                  */
/*==============================================================*/
create table dbo.T_B_UserTypeDayLimit (
   fID                  int                  identity(1, 1),
   fUserTypeID          smallint             not null,
   fPurseID             int                  not null,
   fLimitMoney          money          not null constraint DF__T_B_UserT__fLimi__40F9A68C default (0)
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_B_UserTypeMealLimit                                 */
/*==============================================================*/
create table dbo.T_B_UserTypeMealLimit (
   fID                  int                  identity(1, 1),
   fUserTypeID          smallint             not null,
   fPurseID             int                  not null,
   fMealID              varchar(9)           collate Chinese_PRC_CI_AS not null,
   fLimitCountEnabled   bit                  not null constraint DF__T_B_UserT__fLimi__4707859D default (0),
   fLimitCount          int                  not null constraint DF__T_B_UserT__fLimi__47FBA9D6 default (0),
   fLimitMoneyEnabled   bit                  not null constraint DF__T_B_UserT__fLimi__48EFCE0F default (0),
   fLimitMoney          money          not null constraint DF__T_B_UserT__fLimi__49E3F248 default (0),
   fFirstCount          int                  not null constraint DF__T_B_UserT__fFirs__4AD81681 default (0),
   fFirstDiscount       int                  not null constraint DF__T_B_UserT__fFirs__4BCC3ABA default (100),
   fDiscount            int                  not null constraint DF__T_B_UserT__fDisc__4CC05EF3 default (100)
)
on "PRIMARY"
go

alter table dbo.T_B_UserTypeMealLimit
   add constraint PK_T_B_UserTypeMealLimit primary key (fID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_CardSimRec                                        */
/*==============================================================*/
create table dbo.T_C_CardSimRec (
   fKeyID               int                  identity(1, 1),
   fAccountID           int                  not null,
   fSerialNo            varchar(20)          collate Chinese_PRC_CI_AS not null,
   fPurseID             int                  not null,
   fTranNoS             int                  not null,
   fTranNoE             int                  not null,
   fRecTimeS            datetime             not null constraint DF__T_C_CardS__fRecT__4DB4832C default CONVERT([varchar](10),getdate(),(120)),
   fRecTimeE            datetime             not null constraint DF__T_C_CardS__fRecT__4EA8A765 default CONVERT([varchar](10),getdate(),(120)),
   fOldMoney            money                not null constraint DF__T_C_CardS__fOldM__4F9CCB9E default (0.00),
   fNewMoney            money                not null constraint DF__T_C_CardS__fNewM__5090EFD7 default (0.00),
   fDifference          money                not null constraint DF__T_C_CardS__fDiff__51851410 default (0.00)
)
on "PRIMARY"
go

alter table dbo.T_C_CardSimRec
   add constraint PK__T_C_Card__23D5CF663C34F16F primary key (fKeyID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_CashEmp                                           */
/*==============================================================*/
create table dbo.T_C_CashEmp (
   fkey                 varchar(50)          collate Chinese_PRC_CI_AS not null,
   faccountID           varchar(10)          collate Chinese_PRC_CI_AS null,
   fdate                datetime             null,
   fpurseID             int                  null,
   fmealID              varchar(3)           collate Chinese_PRC_CI_AS null,
   famount              money          null,
   fcount               int                  null,
   famountLimit         money          null,
   fcountLimit          int                  null,
   fRver                timestamp            not null
)
on "PRIMARY"
go

alter table dbo.T_C_CashEmp
   add constraint PK__T_C_Cash__36F01F8119AACF41 primary key (fkey)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_CashEmpEx                                         */
/*==============================================================*/
create table dbo.T_C_CashEmpEx (
   fkey                 varchar(50)          collate Chinese_PRC_CI_AS not null,
   ftype                varchar(2)           collate Chinese_PRC_CI_AS null,
   faccountID           varchar(10)          collate Chinese_PRC_CI_AS null,
   fvalue               int                  null,
   fpurseID             int                  null,
   fmealID              varchar(3)           collate Chinese_PRC_CI_AS null,
   famount              money          null,
   fcount               int                  null,
   famountLimit         money          null,
   fcountLimit          int                  null,
   fRver                timestamp            not null
)
on "PRIMARY"
go

alter table dbo.T_C_CashEmpEx
   add constraint PK__T_C_Cash__36F01F811D7B6025 primary key (fkey)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_Cashdata                                          */
/*==============================================================*/
create table dbo.T_C_Cashdata (
   fKeyID               int                  identity(1, 1),
   fAccount_id          varchar(18)          collate Chinese_PRC_CI_AS not null,
   fCard_Number         varchar(30)          collate Chinese_PRC_CI_AS not null,
   fNewCard_Number      varchar(30)          collate Chinese_PRC_CI_AS not null,
   fAppID               int                  not null constraint DF__T_C_Cashd__fAppI__37703C52 default (0),
   fCons_Time           datetime             not null,
   fCons_State          varchar(2)           collate Chinese_PRC_CI_AS null,
   fCons_Fare           money          not null,
   fStation_id          varchar(2)           collate Chinese_PRC_CI_AS null,
   fSettleTime          datetime             not null constraint DF__T_C_Cashd__fSett__3864608B default getdate(),
   fPosID               int                  not null constraint DF__T_C_Cashd__fPosI__395884C4 default (0)
)
on "PRIMARY"
go

alter table dbo.T_C_Cashdata
   add constraint PK__T_C_Cash__21D8B94D3587F3E0 primary key (fCons_Time, fAccount_id, fCard_Number, fAppID, fCons_Fare)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_Cashdata01                                        */
/*==============================================================*/
create table dbo.T_C_Cashdata01 (
   fKeyID               int                  identity(1, 1),
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS not null,
   fSerialNo            varchar(30)          collate Chinese_PRC_CI_AS not null,
   fPurseID             int                  not null constraint DF__T_C_Cashd__fPurs__2818EA29 default (0),
   fConsTime            datetime             not null,
   fRecType             varchar(2)           collate Chinese_PRC_CI_AS null,
   fAmount              money          not null,
   fStationid           varchar(2)           collate Chinese_PRC_CI_AS null,
   fPosID               int                  not null constraint DF__T_C_Cashd__fPosI__290D0E62 default (0),
   fSettleTime          datetime             not null constraint DF__T_C_Cashd__fSett__2A01329B default getdate()
)
on "PRIMARY"
go

alter table dbo.T_C_Cashdata01
   add constraint PK__T_C_Cash__3C7AA98C2630A1B7 primary key (fConsTime, fAccountID, fSerialNo, fPurseID, fAmount)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_ConsState                                         */
/*==============================================================*/
create table dbo.T_C_ConsState (
   fStateID             int                  not null,
   fStateName           varchar(50)          collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_EmpDayCons                                        */
/*==============================================================*/
create table dbo.T_C_EmpDayCons (
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS not null,
   fSerialNo            varchar(30)          collate Chinese_PRC_CI_AS not null,
   fCons_Day            datetime             null,
   fConsCount           int                  null constraint DF__T_C_EmpDa__fCons__52793849 default (0),
   fConsMoney           money         null constraint DF__T_C_EmpDa__fCons__536D5C82 default (0.00),
   fMealCount1          int                  null constraint DF__T_C_EmpDa__fMeal__546180BB default (0),
   fMealCons1           money         null constraint DF__T_C_EmpDa__fMeal__5555A4F4 default (0.00),
   fMealCount2          int                  null constraint DF__T_C_EmpDa__fMeal__5649C92D default (0),
   fMealCons2           money         null constraint DF__T_C_EmpDa__fMeal__573DED66 default (0.00),
   fMealCount3          int                  null constraint DF__T_C_EmpDa__fMeal__5832119F default (0),
   fMealCons3           money         null constraint DF__T_C_EmpDa__fMeal__592635D8 default (0.00),
   fMealCount4          int                  null constraint DF__T_C_EmpDa__fMeal__5A1A5A11 default (0),
   fMealCons4           money         null constraint DF__T_C_EmpDa__fMeal__5B0E7E4A default (0.00),
   fMealCount5          int                  null constraint DF__T_C_EmpDa__fMeal__5C02A283 default (0),
   fMealCons5           money         null constraint DF__T_C_EmpDa__fMeal__5CF6C6BC default (0.00),
   fMealCount6          int                  null constraint DF__T_C_EmpDa__fMeal__5DEAEAF5 default (0),
   fMealCons6           money         null constraint DF__T_C_EmpDa__fMeal__5EDF0F2E default (0.00),
   fMealCount7          int                  null constraint DF__T_C_EmpDa__fMeal__5FD33367 default (0),
   fMealCons7           money         null constraint DF__T_C_EmpDa__fMeal__60C757A0 default (0.00),
   fMealCount8          int                  null constraint DF__T_C_EmpDa__fMeal__61BB7BD9 default (0),
   fMealCons8           money         null constraint DF__T_C_EmpDa__fMeal__62AFA012 default (0.00),
   fJcCount             int                  null constraint DF_T_C_EmpDayCons_fJcCount default (0),
   fMealJcCount1        int                  null constraint DF_T_C_EmpDayCons_fMealJcCount1 default (0),
   fMealJcCount2        int                  null constraint DF_T_C_EmpDayCons_fMealJcCount2 default (0),
   fMealJcCount3        int                  null constraint DF_T_C_EmpDayCons_fMealJcCount3 default (0),
   fMealJcCount4        int                  null constraint DF_T_C_EmpDayCons_fMealJcCount4 default (0),
   fMealJcCount5        int                  null constraint DF_T_C_EmpDayCons_fMealJcCount5 default (0),
   fMealJcCount6        int                  null constraint DF_T_C_EmpDayCons_fMealJcCount6 default (0),
   fMealJcCount7        int                  null constraint DF_T_C_EmpDayCons_fMealJcCount7 default (0),
   fMealJcCount8        int                  null constraint DF_T_C_EmpDayCons_fMealJcCount8 default (0)
)
on "PRIMARY"
go

alter table dbo.T_C_EmpDayCons
   add constraint PK_T_C_EmpDayCons primary key (fAccountID, fSerialNo)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_ErrRec                                            */
/*==============================================================*/
create table dbo.T_C_ErrRec (
   fKeyID               bigint               identity(1, 1),
   fAccount_id          varchar(18)          collate Chinese_PRC_CI_AS null,
   fCard_Number         varchar(12)          collate Chinese_PRC_CI_AS null,
   fPos_id              varchar(5)           collate Chinese_PRC_CI_AS null,
   fDp_bh               varchar(18)          collate Chinese_PRC_CI_AS null,
   fCons_State          varchar(2)           collate Chinese_PRC_CI_AS null,
   fCons_Time           datetime             null,
   fGatherTime          datetime             null,
   fOdd_Money           money         null constraint DF__T_C_ErrRe__fOdd___6C390A4C default (0),
   fCons_Fare           money         null constraint DF__T_C_ErrRe__fCons__6D2D2E85 default (0),
   fX_Money             money         null constraint DF__T_C_ErrRe__fX_Mo__6E2152BE default (0),
   fOper_id             varchar(20)          collate Chinese_PRC_CI_AS null,
   fMeal_id             varchar(3)           collate Chinese_PRC_CI_AS null,
   fStation_id          varchar(2)           collate Chinese_PRC_CI_AS null,
   fSx_Money            money         null constraint DF__T_C_ErrRe__fSx_M__6F1576F7 default (0),
   fManageMoney         money         null constraint DF__T_C_ErrRe__fMana__70099B30 default (0),
   fMenuID              varchar(10)          collate Chinese_PRC_CI_AS null,
   fFKTIME              int                  null constraint DF__T_C_ErrRe__fFKTI__70FDBF69 default (0),
   fX_SubMoney          money         null,
   fCpID                int                  null,
   fCpCount             int                  null,
   fSettleTime          datetime             null,
   fRecKey              varchar(200)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_C_ErrRec
   add constraint PK__T_C_ErrRec primary key (fKeyID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_Esubsity                                          */
/*==============================================================*/
create table dbo.T_C_Esubsity (
   Id                   bigint               not null,
   Account_id           varchar(8)           collate Chinese_PRC_CI_AS not null,
   name                 varchar(50)          collate Chinese_PRC_CI_AS not null,
   dp_bh                varchar(50)          collate Chinese_PRC_CI_AS not null,
   dp_name              varchar(50)          collate Chinese_PRC_CI_AS not null,
   Subsity_Money        money         not null,
   Subsity_time         datetime             not null,
   Subsitylqtime        datetime             not null,
   Oper_id              smallint             not null,
   Subsity_ok           smallint             not null
)
on "PRIMARY"
go

alter table dbo.T_C_Esubsity
   add constraint PK__T_C_Esubsity primary key (Id)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_FrozenRec                                         */
/*==============================================================*/
create table dbo.T_C_FrozenRec (
   fID                  int                  identity(1, 1),
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS null,
   fCardNo              varchar(12)          collate Chinese_PRC_CI_AS null,
   fTime                datetime             null,
   fChecked             bit                  not null constraint DF__T_C_Froze__fChec__71F1E3A2 default (0),
   fCheckTime           datetime             null,
   fDesc                varchar(100)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_C_FrozenRec
   add constraint PK_T_C_FrozenRec primary key (fID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_OverdueRec                                        */
/*==============================================================*/
create table dbo.T_C_OverdueRec (
   fKeyID               bigint               identity(1, 1),
   fAccount_id          varchar(18)          collate Chinese_PRC_CI_AS null,
   fCard_Number         varchar(12)          collate Chinese_PRC_CI_AS null,
   fPos_id              varchar(5)           collate Chinese_PRC_CI_AS null,
   fDp_bh               varchar(18)          collate Chinese_PRC_CI_AS null,
   fCons_State          varchar(2)           collate Chinese_PRC_CI_AS null,
   fCons_Time           datetime             null,
   fGatherTime          datetime             null,
   fOdd_Money           money         null constraint DF__T_C_Overd__fOdd___72E607DB default (0),
   fCons_Fare           money         null constraint DF__T_C_Overd__fCons__73DA2C14 default (0),
   fX_Money             money         null constraint DF__T_C_Overd__fX_Mo__74CE504D default (0),
   fX_SubMoney          money         null,
   fOper_id             varchar(20)          collate Chinese_PRC_CI_AS null,
   fMeal_id             varchar(3)           collate Chinese_PRC_CI_AS null,
   fStation_id          varchar(2)           collate Chinese_PRC_CI_AS null,
   fSx_Money            money         null constraint DF__T_C_Overd__fSx_M__75C27486 default (0),
   fManageMoney         money         null constraint DF__T_C_Overd__fMana__76B698BF default (0),
   fMenuID              varchar(10)          collate Chinese_PRC_CI_AS null,
   fFKTIME              int                  null constraint DF__T_C_Overd__fFKTI__77AABCF8 default (0),
   fCpID                int                  null,
   fCpCount             int                  null,
   fSettleTime          datetime             null,
   fRecKey              varchar(200)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_C_OverdueRec
   add constraint PK__T_C_OverdueRec unique (fKeyID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_PendingConsRec                                    */
/*==============================================================*/
create table dbo.T_C_PendingConsRec (
   fKeyID               int                  identity(1, 1),
   fPurseID             int                  null,
   fFlowType            int                  null,
   fRecType             int                  null,
   fUserCardID          varchar(16)          collate Chinese_PRC_CI_AS null,
   fPosID               int                  null,
   fCreateTime          datetime             null,
   fRecvTime            datetime             null,
   fAmount              money         null,
   fDiscount            money         null,
   fSourceID            int                  null,
   fTaskID              int                  null,
   fOperID              int                  null,
   fFee1                money         null,
   fFee2                money         null,
   fFee3                money         null,
   fFee4                money         null,
   fOffTranNo           int                  null,
   fPosTranNo           int                  null,
   fPosOffTranNo        int                  null,
   ffRecKey             varchar(200)         collate Chinese_PRC_CI_AS null,
   ffExternalOrder      varchar(100)         collate Chinese_PRC_CI_AS null,
   fDealState           int                  not null constraint DF__T_C_Pendi__fDeal__4316F928 default (0),
   fDealTime            datetime             null
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_PreCashier                                        */
/*==============================================================*/
create table dbo.T_C_PreCashier (
   fKeyID               int                  identity(1, 1),
   fconsstate           varchar(4)           collate Chinese_PRC_CI_AS null,
   fSucc                varchar(4)           collate Chinese_PRC_CI_AS null,
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS null,
   fCardNo              varchar(18)          collate Chinese_PRC_CI_AS null,
   fPosID               varchar(8)           collate Chinese_PRC_CI_AS null,
   fFkTime              int                  null,
   fOldMoney            money         null,
   fConsFare            money         null,
   fNewMoney            money         null,
   fConsTime            datetime             null,
   fOperID              varchar(20)          collate Chinese_PRC_CI_AS null,
   fMark                varchar(30)          collate Chinese_PRC_CI_AS null,
   fMarkTime            datetime             null constraint DF__T_C_PreCa__fMark__789EE131 default '2000-01-01'
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_REC_Repeat                                        */
/*==============================================================*/
create table dbo.T_C_REC_Repeat (
   fAutoID              int                  identity(1, 1),
   fPurseID             int                  null,
   fFlowType            int                  null,
   fRecType             int                  null,
   fUserCardID          varchar(16)          collate Chinese_PRC_CI_AS null,
   fPosID               int                  null,
   fCreateTime          datetime             null,
   fRecvTime            datetime             null,
   fAmount              money         null,
   fDiscount            money         null,
   fSourceID            int                  null,
   fTaskID              int                  null,
   fOperID              int                  null,
   fFee1                money         null,
   fFee2                money         null,
   fFee3                money         null,
   fFee4                money         null,
   fOffTranNo           int                  null,
   fPosTranNo           int                  null,
   fPosOffTranNo        int                  null,
   ffRecKey             varchar(200)         collate Chinese_PRC_CI_AS null,
   ffExternalOrder      varchar(100)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_RecC_Example                                      */
/*==============================================================*/
create table dbo.T_C_RecC_Example (
   fAutoID              int                  identity(1, 1),
   fKeyID               bigint               not null,
   fAccount_id          varchar(18)          collate Chinese_PRC_CI_AS not null,
   fCard_Number         varchar(12)          collate Chinese_PRC_CI_AS null,
   fFKTIME              int                  not null,
   fAppID               int                  not null constraint DF__T_C_RecC___fAppI__7A8729A3 default (0),
   fCons_State          varchar(2)           collate Chinese_PRC_CI_AS not null,
   fCons_Time           datetime             not null,
   fOdd_Money           money          not null,
   fCons_Fare           money          not null,
   fX_Money             money          not null,
   fSx_Money            money          null,
   fManageMoney         money          null,
   fPos_id              varchar(5)           collate Chinese_PRC_CI_AS not null,
   fPOSTrNo             int                  null constraint DF__T_C_RecC___fPOST__7B7B4DDC default (0),
   fStation_id          varchar(2)           collate Chinese_PRC_CI_AS null,
   fDp_bh               varchar(18)          collate Chinese_PRC_CI_AS null,
   fGatherTime          datetime             null,
   fSettleTime          datetime             null,
   fOper_id             varchar(20)          collate Chinese_PRC_CI_AS null,
   fMeal_id             varchar(3)           collate Chinese_PRC_CI_AS null,
   fCpID                int                  null,
   fCpCount             int                  null,
   fMenuID              varchar(10)          collate Chinese_PRC_CI_AS null,
   fPhysicalNo          varchar(30)          collate Chinese_PRC_CI_AS null,
   fRecKey              varchar(200)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_C_RecC_Example
   add constraint PK__T_C_RecC__DF8F04D30F19C8E3 primary key (fAccount_id, fFKTIME, fAppID, fCons_State, fCons_Time, fX_Money, fPos_id)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_RecS_Example                                      */
/*==============================================================*/
create table dbo.T_C_RecS_Example (
   fAutoID              int                  identity(1, 1),
   fKeyID               bigint               not null,
   fAccount_id          varchar(18)          collate Chinese_PRC_CI_AS not null,
   fCard_Number         varchar(12)          collate Chinese_PRC_CI_AS null,
   fFKTIME              int                  not null,
   fAppID               int                  not null constraint DF__T_C_RecS___fAppI__7C6F7215 default (0),
   fCons_State          varchar(2)           collate Chinese_PRC_CI_AS not null,
   fCons_Time           datetime             not null,
   fOdd_Money           money          not null,
   fCons_Fare           money          not null,
   fX_Money             money          not null,
   fSx_Money            money          null,
   fManageMoney         money          null,
   fPos_id              varchar(5)           collate Chinese_PRC_CI_AS not null,
   fPOSTrNo             int                  null constraint DF__T_C_RecS___fPOST__7D63964E default (0),
   fStation_id          varchar(2)           collate Chinese_PRC_CI_AS null,
   fDp_bh               varchar(18)          collate Chinese_PRC_CI_AS null,
   fGatherTime          datetime             null,
   fSettleTime          datetime             null,
   fOper_id             varchar(20)          collate Chinese_PRC_CI_AS null,
   fMeal_id             varchar(3)           collate Chinese_PRC_CI_AS null,
   fCpID                int                  null,
   fCpCount             int                  null,
   fMenuID              varchar(10)          collate Chinese_PRC_CI_AS null,
   fPhysicalNo          varchar(30)          collate Chinese_PRC_CI_AS null,
   fRecKey              varchar(200)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_C_RecS_Example
   add constraint PK__T_C_RecS__DF8F04D315C6C672 primary key (fAccount_id, fFKTIME, fAppID, fCons_State, fCons_Time, fX_Money, fPos_id)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_Rec_OverdueRec                                    */
/*==============================================================*/
create table dbo.T_C_Rec_OverdueRec (
   fAutoID              int                  identity(1, 1),
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS not null,
   fSerialNo            varchar(30)          collate Chinese_PRC_CI_AS not null,
   fPurseID             int                  not null,
   fRecType             int                  not null,
   fPosID               varchar(5)           collate Chinese_PRC_CI_AS not null,
   fCreateTime          datetime             not null,
   fRecvTime            datetime             not null,
   fAmount              money          not null,
   fDiscount            money          null,
   fSourceID            int                  not null,
   fCardTranNo          int                  not null,
   fPosTranNo           int                  null,
   fMealID              varchar(3)           collate Chinese_PRC_CI_AS null,
   fRecKey              varchar(200)         collate Chinese_PRC_CI_AS null,
   fExternalOrder       varchar(100)         collate Chinese_PRC_CI_AS not null constraint DF__T_C_Rec_O__fExte__45F365D3 default ''
)
on "PRIMARY"
go

alter table dbo.T_C_Rec_OverdueRec
   add constraint PK_T_C_Rec_OverdueRec primary key (fCreateTime, fAccountID, fSerialNo, fPurseID, fRecType, fAmount, fPosID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_Rec_Reverse                                       */
/*==============================================================*/
create table dbo.T_C_Rec_Reverse (
   fID                  int                  identity(1, 1),
   fKeyID               bigint               not null,
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS null,
   fCardNo              varchar(30)          collate Chinese_PRC_CI_AS null,
   fconsFare            money          not null,
   fFKTIME              int                  not null,
   fTime                datetime             null,
   fDesc                varchar(20)          collate Chinese_PRC_CI_AS null,
   fPurseID             int                  null constraint DF__T_C_Rec_R__fPurs__7993056A default (0)
)
on "PRIMARY"
go

alter table dbo.T_C_Rec_Reverse
   add constraint PK_T_C_Rec_Reverse primary key (fID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_Rec_Unconfirmed                                   */
/*==============================================================*/
create table dbo.T_C_Rec_Unconfirmed (
   fAutoID              int                  identity(1, 1),
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS not null,
   fSerialNo            varchar(30)          collate Chinese_PRC_CI_AS not null,
   fPurseID             int                  not null,
   fRecType             int                  not null,
   fPosID               varchar(5)           collate Chinese_PRC_CI_AS not null,
   fCreateTime          datetime             not null,
   fRecvTime            datetime             not null,
   fAmount              money          not null,
   fDiscount            money          null,
   fSourceID            int                  not null,
   fCardTranNo          int                  not null,
   fPosTranNo           int                  null,
   fMealID              varchar(3)           collate Chinese_PRC_CI_AS null,
   fRecKey              varchar(200)         collate Chinese_PRC_CI_AS null,
   fExternalOrder       varchar(100)         collate Chinese_PRC_CI_AS not null constraint DF__T_C_Rec_U__fExte__245D67DE default ''
)
on "PRIMARY"
go

alter table dbo.T_C_Rec_Unconfirmed
   add constraint PK_T_C_Rec_Unconfirmed primary key (fCreateTime, fAccountID, fSerialNo, fPurseID, fRecType, fAmount, fPosID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_SUM_OPER                                          */
/*==============================================================*/
create table dbo.T_C_SUM_OPER (
   fKey                 varchar(30)          collate Chinese_PRC_CI_AS not null,
   fOperID              int                  not null,
   fDate                datetime             not null,
   fMealID              varchar(3)           collate Chinese_PRC_CI_AS not null,
   fTType               int                  not null,
   fCType               int                  not null,
   fMoney               money         not null constraint DF__T_C_SUM_O__fMone__0ABD916C default (0.00),
   fCount               int                  not null constraint DF__T_C_SUM_O__fCoun__0BB1B5A5 default (0),
   fAppID               int                  not null constraint DF__T_C_SUM_O__fAppI__0CA5D9DE default (0)
)
on "PRIMARY"
go

alter table dbo.T_C_SUM_OPER
   add constraint PK_T_C_SUM_OPER primary key (fKey, fTType, fCType, fAppID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_SUM_Pos                                           */
/*==============================================================*/
create table dbo.T_C_SUM_Pos (
   fKey                 varchar(30)          collate Chinese_PRC_CI_AS not null,
   fPosID               int                  not null,
   fDate                datetime             not null,
   fMealID              varchar(3)           collate Chinese_PRC_CI_AS not null,
   fTType               int                  not null,
   fCType               int                  not null,
   fMoney               money         not null constraint DF__T_C_SUM_P__fMone__1C873BEC default (0.00),
   fCount               int                  not null constraint DF__T_C_SUM_P__fCoun__1D7B6025 default (0),
   fDiscount            money         not null constraint DF_T_C_SUM_Pos_fDiscount default (0.00),
   fPurseID             int                  not null constraint DF__T_C_SUM_P__fAppI__1E6F845E default (0)
)
on "PRIMARY"
go

alter table dbo.T_C_SUM_Pos
   add constraint PK_T_C_SUM_POS primary key (fKey, fTType, fCType, fPurseID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_SimRec                                            */
/*==============================================================*/
create table dbo.T_C_SimRec (
   fID                  int                  identity(1, 1),
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS not null,
   fbfktime             int                  not null,
   fefktime             int                  not null,
   fConsfare            money         not null,
   fOmoney              money         not null,
   fNmoney              money         null,
   fState               int                  not null,
   fSimdate             datetime             null,
   fSubAppID            int                  null
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_SubHistory                                        */
/*==============================================================*/
create table dbo.T_C_SubHistory (
   fKeyID               bigint               not null,
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS not null,
   fSubMoney            money                not null,
   fSubTime             datetime             not null,
   fReceiveTime         datetime             null,
   fOperID              smallint             not null,
   fReceived            bit                  not null,
   fStartReceiveDate    datetime             not null constraint DF__T_C_SubHi__fStar__7E57BA87 default getdate(),
   fEndReceiveDate      datetime             not null constraint DF__T_C_SubHi__fEndR__7F4BDEC0 default getdate(),
   fYear                int                  not null constraint DF__T_C_SubHi__fYear__004002F9 default datepart(year,getdate()),
   fMonth               int                  not null constraint DF__T_C_SubHi__fMont__01342732 default datepart(month,getdate()),
   fReason              bit                  not null constraint DF__T_C_SubHi__fReas__02284B6B default (0),
   fSubID               int                  null,
   fRequested           int                  not null constraint DF__T_C_SubHi__fRequ__031C6FA4 default (0),
   fLastMoney           money                null
)
on "PRIMARY"
go

alter table dbo.T_C_SubHistory
   add constraint PK__T_C_SubHistory primary key (fKeyID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_Subsidizes                                        */
/*==============================================================*/
create table dbo.T_C_Subsidizes (
   fKeyID               bigint               identity(1, 1),
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS not null,
   fSubMoney            money                not null,
   fSubTime             datetime             not null,
   fReceiveTime         datetime             null,
   fOperID              smallint             not null,
   fReceived            bit                  not null,
   fStartReceiveDate    datetime             not null constraint DF__T_C_Subsi__fStar__041093DD default getdate(),
   fEndReceiveDate      datetime             not null constraint DF__T_C_Subsi__fEndR__0504B816 default getdate(),
   fYear                int                  not null constraint DF__T_C_Subsi__fYear__05F8DC4F default datepart(year,getdate()),
   fMonth               int                  not null constraint DF__T_C_Subsi__fMont__06ED0088 default datepart(month,getdate()),
   fClearSub            smallint             not null constraint DF__T_C_Subsi__fClea__07E124C1 default (0),
   fSubID               int                  null,
   fRequested           int                  not null constraint DF__T_C_Subsi__fRequ__08D548FA default (0),
   fLastMoney           money                null,
   fPurseCode           int                  null constraint DF__T_C_Subsi__fPurs__09C96D33 default (0)
)
on "PRIMARY"
go

alter table dbo.T_C_Subsidizes
   add constraint PK__T_C_Subsidizes primary key (fKeyID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_SumEmpDealByDay                                   */
/*==============================================================*/
create table dbo.T_C_SumEmpDealByDay (
   fKeyID               int                  identity(1, 1),
   fDate                varchar(10)          collate Chinese_PRC_CI_AS null,
   fCreateTime          datetime             null,
   fOpreID              int                  null
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_SysAccontdDay                                     */
/*==============================================================*/
create table dbo.T_C_SysAccontdDay (
   fDate                datetime             not null,
   fOldAcount           int                  not null,
   fOldAcountMoney      money         null,
   fConsCount           int                  not null,
   fConsMoney           money         null,
   fkhCount             int                  not null,
   fKhtlSum             money         null,
   fKhDpsit             money         null,
   fKhPndge             money         null,
   fKhManage            money         null,
   fChCount             int                  not null,
   fChtlSum             money         null,
   fChPndge             money         null,
   fChMoney             money         null,
   fChTkMoney           money         null,
   fSvCount             int                  not null,
   fSvtlSum             money         null,
   fSvPndge             money         null,
   fTkCount             int                  not null,
   fTktlSum             money         null,
   fGsCount             int                  not null,
   fGsPndge             money         null,
   fJgCount             int                  not null,
   fJgPndge             money         null,
   fHkCount             int                  not null,
   fHkPndge             money         null,
   fBkCount             int                  not null,
   fBktlSum             money         null,
   fBkPndge             money         null,
   fJcCount             int                  not null,
   fJctlSum             money         null,
   fSbCount             int                  not null,
   fSbtlSum             money         null,
   fSbClearCount        int                  not null,
   fSbClearSum          money         null,
   fQCCount             int                  not null,
   fQCtlSum             money         null,
   fQCBXCount           int                  not null,
   fQCBXtlSum           money         null,
   fNewAcount           int                  not null,
   fNewAcountMoney      money         null,
   fOldAcountMoneyJC    int                  not null constraint DF__T_C_SysAc__fOldA__09A971A2 default (0),
   fNewAcountMoneyJC    int                  not null constraint DF__T_C_SysAc__fNewA__0A9D95DB default (0),
   fConsMoneyJC         int                  not null constraint DF__T_C_SysAc__fCons__0B91BA14 default (0),
   fSbCountJC           int                  not null constraint DF__T_C_SysAc__fSbCo__0C85DE4D default (0),
   fSbtlSumJC           int                  not null constraint DF__T_C_SysAc__fSbtl__0D7A0286 default (0),
   fSbClearCountJC      int                  not null constraint DF__T_C_SysAc__fSbCl__0E6E26BF default (0),
   fSbClearSumJC        int                  not null constraint DF__T_C_SysAc__fSbCl__0F624AF8 default (0),
   fJcCountJC           int                  not null constraint DF__T_C_SysAc__fJcCo__10566F31 default (0),
   fJctlSumJC           int                  not null constraint DF__T_C_SysAc__fJctl__114A936A default (0),
   fSaveCountJC         int                  not null constraint DF__T_C_SysAc__fSave__123EB7A3 default (0),
   fSaveMoneyJC         int                  not null constraint DF__T_C_SysAc__fSave__1332DBDC default (0),
   fTakeCountJC         int                  not null constraint DF__T_C_SysAc__fTake__14270015 default (0),
   fTakeMoneyJC         int                  not null constraint DF__T_C_SysAc__fTake__151B244E default (0)
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_SysAccontdToDay                                   */
/*==============================================================*/
create table dbo.T_C_SysAccontdToDay (
   fDate                datetime             not null,
   fOldAcount           int                  not null,
   fOldAcountMoney      money         null,
   fConsCount           int                  not null,
   fConsMoney           money         null,
   fkhCount             int                  not null,
   fKhtlSum             money         null,
   fKhDpsit             money         null,
   fKhPndge             money         null,
   fKhManage            money         null,
   fChCount             int                  not null,
   fChtlSum             money         null,
   fChPndge             money         null,
   fChMoney             money         null,
   fChTkMoney           money         null,
   fSvCount             int                  not null,
   fSvtlSum             money         null,
   fSvPndge             money         null,
   fTkCount             int                  not null,
   fTktlSum             money         null,
   fGsCount             int                  not null,
   fGsPndge             money         null,
   fJgCount             int                  not null,
   fJgPndge             money         null,
   fHkCount             int                  not null,
   fHkPndge             money         null,
   fBkCount             int                  not null,
   fBktlSum             money         null,
   fBkPndge             money         null,
   fJcCount             int                  not null,
   fJctlSum             money         null,
   fSbCount             int                  not null,
   fSbtlSum             money         null,
   fSbClearCount        int                  not null,
   fSbClearSum          money         null,
   fQCCount             int                  not null,
   fQCtlSum             money         null,
   fQCBXCount           int                  not null,
   fQCBXtlSum           money         null,
   fNewAcount           int                  not null,
   fNewAcountMoney      money         null,
   fOldAcountMoneyJC    int                  not null constraint DF__T_C_SysAc__fOldA__7C4F7684 default (0),
   fNewAcountMoneyJC    int                  not null constraint DF__T_C_SysAc__fNewA__7D439ABD default (0),
   fConsMoneyJC         int                  not null constraint DF__T_C_SysAc__fCons__7E37BEF6 default (0),
   fSbCountJC           int                  not null constraint DF__T_C_SysAc__fSbCo__7F2BE32F default (0),
   fSbtlSumJC           int                  not null constraint DF__T_C_SysAc__fSbtl__00200768 default (0),
   fSbClearCountJC      int                  not null constraint DF__T_C_SysAc__fSbCl__01142BA1 default (0),
   fSbClearSumJC        int                  not null constraint DF__T_C_SysAc__fSbCl__02084FDA default (0),
   fJcCountJC           int                  not null constraint DF__T_C_SysAc__fJcCo__02FC7413 default (0),
   fJctlSumJC           int                  not null constraint DF__T_C_SysAc__fJctl__03F0984C default (0),
   fSaveCountJC         int                  not null constraint DF__T_C_SysAc__fSave__04E4BC85 default (0),
   fSaveMoneyJC         int                  not null constraint DF__T_C_SysAc__fSave__05D8E0BE default (0),
   fTakeCountJC         int                  not null constraint DF__T_C_SysAc__fTake__06CD04F7 default (0),
   fTakeMoneyJC         int                  not null constraint DF__T_C_SysAc__fTake__07C12930 default (0)
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_SysAccount                                        */
/*==============================================================*/
create table dbo.T_C_SysAccount (
   fid                  bigint               identity(1, 1),
   fOperName            varchar(20)          collate Chinese_PRC_CI_AS not null,
   fBeginDate           datetime             not null,
   fEndDate             datetime             not null,
   fOperDate            datetime             not null,
   fOAcount             int                  not null constraint DF__T_C_SysAc__fOAco__116A8EFB default (0),
   fOAcountMoney        money         not null constraint DF__T_C_SysAc__fOAco__125EB334 default (0.00),
   fNAcount             int                  not null constraint DF__T_C_SysAc__fNAco__1352D76D default (0),
   fNAcountMoney        money         not null constraint DF__T_C_SysAc__fNAco__1446FBA6 default (0.00),
   fConsCount           int                  not null constraint DF__T_C_SysAc__fCons__153B1FDF default (0),
   fConsMoney           money         not null constraint DF__T_C_SysAc__fCons__162F4418 default (0.00),
   fkhCount             int                  not null constraint DF__T_C_SysAc__fkhCo__17236851 default (0),
   fKhtlSum             money         not null constraint DF__T_C_SysAc__fKhtl__18178C8A default (0.00),
   fKhDpsit             money         not null constraint DF__T_C_SysAc__fKhDp__190BB0C3 default (0.00),
   fKhPndge             money         not null constraint DF__T_C_SysAc__fKhPn__19FFD4FC default (0.00),
   fKhManage            money         not null constraint DF__T_C_SysAc__fKhMa__1AF3F935 default (0.00),
   fChCount             int                  not null constraint DF__T_C_SysAc__fChCo__1BE81D6E default (0),
   fChtlSum             money         not null constraint DF__T_C_SysAc__fChtl__1CDC41A7 default (0.00),
   fChMoney             money         not null constraint DF__T_C_SysAc__fChMo__1DD065E0 default (0.00),
   fChPndge             money         not null constraint DF__T_C_SysAc__fChPn__1EC48A19 default (0.00),
   fGsCount             int                  not null constraint DF__T_C_SysAc__fGsCo__1FB8AE52 default (0),
   fGsPndge             money         not null constraint DF__T_C_SysAc__fGsPn__20ACD28B default (0.00),
   fJgCount             int                  not null constraint DF__T_C_SysAc__fJgCo__21A0F6C4 default (0),
   fJgPndge             money         not null constraint DF__T_C_SysAc__fJgPn__22951AFD default (0.00),
   fSvCount             int                  not null constraint DF__T_C_SysAc__fSvCo__23893F36 default (0),
   fSvPndge             money         not null constraint DF__T_C_SysAc__fSvPn__247D636F default (0.00),
   fSvtlSum             money         not null constraint DF__T_C_SysAc__fSvtl__257187A8 default (0.00),
   fTkCount             int                  not null constraint DF__T_C_SysAc__fTkCo__2665ABE1 default (0),
   fTktlSum             money         not null constraint DF__T_C_SysAc__fTktl__2759D01A default (0.00),
   fHkCount             int                  not null constraint DF__T_C_SysAc__fHkCo__284DF453 default (0),
   fHkPndge             money         not null constraint DF__T_C_SysAc__fHkPn__2942188C default (0.00),
   fBkCount             int                  not null constraint DF__T_C_SysAc__fBkCo__2A363CC5 default (0),
   fBktlSum             money         not null constraint DF__T_C_SysAc__fBktl__2B2A60FE default (0.00),
   fBkPndge             money         not null constraint DF__T_C_SysAc__fBkPn__2C1E8537 default (0.00),
   fJcCount             int                  not null constraint DF__T_C_SysAc__fJcCo__2D12A970 default (0),
   fJctlSum             money         not null constraint DF__T_C_SysAc__fJctl__2E06CDA9 default (0.00),
   fSbCount             int                  not null constraint DF__T_C_SysAc__fSbCo__2EFAF1E2 default (0),
   fSbtlSum             money         not null constraint DF__T_C_SysAc__fSbtl__2FEF161B default (0.00),
   fCheck               varchar(4)           collate Chinese_PRC_CI_AS null,
   fCheckOperName       varchar(20)          collate Chinese_PRC_CI_AS null,
   fCheckDate           datetime             not null constraint DF__T_C_SysAc__fChec__30E33A54 default '2000-01-01',
   fRecKey              varchar(1000)        collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_C_SysAccount
   add constraint PK_T_C_SYSACCOUNT primary key (fid)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_TaskSubsidy                                       */
/*==============================================================*/
create table dbo.T_C_TaskSubsidy (
   fKeyID               int                  identity(1, 1),
   fPlanID              int                  not null,
   fObjectID            varchar(20)          collate Chinese_PRC_CI_AS null,
   fPurseID             int                  not null,
   fSubType             int                  not null constraint DF__T_C_TaskS__fSubT__31D75E8D default (0),
   fSubMoney            money                not null constraint DF__T_C_TaskS__fSubM__32CB82C6 default (0),
   fRemark              varchar(200)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_C_TaskSubsidy
   add constraint PK_T_C_TaskSubsidy primary key (fKeyID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_middle_Step1                                      */
/*==============================================================*/
create table dbo.T_C_middle_Step1 (
   fKeyID               bigint               identity(1, 1),
   fPurseID             int                  null,
   fRecType             int                  null,
   fAccountID           varchar(10)          collate Chinese_PRC_CI_AS null,
   fUserCardID          varchar(16)          collate Chinese_PRC_CI_AS null,
   fPosID               int                  null,
   fStationID           varchar(10)          collate Chinese_PRC_CI_AS null,
   fMealID              varchar(10)          collate Chinese_PRC_CI_AS null,
   fCreateTime          datetime             null,
   fRecvTime            datetime             null,
   fOldMoney            money         null,
   fAmount              money         null,
   fBalance             money         null,
   fDiscount            money         null,
   fOperID              int                  null,
   fFee1                money         null,
   fFee2                money         null,
   fFee3                money         null,
   fFee4                money         null,
   fLimitCountEnabled   bit                  null,
   fFlowType            int                  not null constraint DF__T_C_middl__fFlow__7EF6D905 default (0),
   fSourceID            int                  not null constraint DF__T_C_middl__fSour__7FEAFD3E default (0),
   fTaskID              int                  not null constraint DF__T_C_middl__fTask__00DF2177 default (0),
   fOffTranNo           int                  not null constraint DF__T_C_middl__fOffT__01D345B0 default (0),
   fPosTranNo           int                  not null constraint DF__T_C_middl__fPosT__02C769E9 default (0),
   fPosOffTranNo        int                  not null constraint DF__T_C_middl__fPosO__03BB8E22 default (0),
   ffRecKey             varchar(200)         collate Chinese_PRC_CI_AS not null constraint DF__T_C_middl__ffRec__04AFB25B default '',
   ffExternalOrder      varchar(100)         collate Chinese_PRC_CI_AS not null constraint DF__T_C_middl__ffExt__05A3D694 default '',
   fIsRepeatWater       int                  not null constraint DF__T_C_middl__fIsRe__0697FACD default (0),
   fIsPendingConsRec    int                  not null constraint DF__T_C_middl__fIsPe__078C1F06 default (0)
)
on "PRIMARY"
go

alter table dbo.T_C_middle_Step1
   add constraint PK__T_C_midd__23D5CF667D0E9093 primary key (fKeyID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_C_middle_Step2                                      */
/*==============================================================*/
create table dbo.T_C_middle_Step2 (
   fKeyID               bigint               identity(1, 1),
   fPurseID             int                  null,
   fRecType             int                  null,
   fAccountID           varchar(16)          collate Chinese_PRC_CI_AS null,
   fPosID               int                  null,
   fMealID              varchar(3)           collate Chinese_PRC_CI_AS null,
   fRecvTime            datetime             null,
   fOldMoney            money         null,
   fAmount              money         null,
   fBalance             money         null,
   fDiscount            money         null,
   fOperID              int                  null,
   fFee1                money         null,
   fFee2                money         null,
   fFee3                money         null,
   fFee4                money         null,
   fLimitCountEnabled   bit                  null,
   fUserCardID          varchar(16)          collate Chinese_PRC_CI_AS not null constraint DF__T_C_middl__fUser__0C50D423 default '',
   fStationID           varchar(10)          collate Chinese_PRC_CI_AS not null constraint DF__T_C_middl__fStat__0D44F85C default '',
   fCreateTime          datetime             not null constraint DF__T_C_middl__fCrea__0E391C95 default (0),
   fFlowType            int                  not null constraint DF__T_C_middl__fFlow__0F2D40CE default (0),
   fSourceID            int                  not null constraint DF__T_C_middl__fSour__10216507 default (0),
   fTaskID              int                  not null constraint DF__T_C_middl__fTask__11158940 default (0),
   fOffTranNo           int                  not null constraint DF__T_C_middl__fOffT__1209AD79 default (0),
   fPosTranNo           int                  not null constraint DF__T_C_middl__fPosT__12FDD1B2 default (0),
   fPosOffTranNo        int                  not null constraint DF__T_C_middl__fPosO__13F1F5EB default (0),
   ffRecKey             varchar(200)         collate Chinese_PRC_CI_AS not null constraint DF__T_C_middl__ffRec__14E61A24 default '',
   ffExternalOrder      varchar(100)         collate Chinese_PRC_CI_AS not null constraint DF__T_C_middl__ffExt__15DA3E5D default ''
)
on "PRIMARY"
go

alter table dbo.T_C_middle_Step2
   add constraint PK__T_C_midd__23D5CF660A688BB1 primary key (fKeyID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_E_CardReader                                        */
/*==============================================================*/
create table dbo.T_E_CardReader (
   fKeyID               int                  identity(1, 1),
   fReaderID            int                  not null,
   fReaderCode          varchar(9)           collate Chinese_PRC_CI_AS null,
   fPosID               int                  not null constraint DF__T_E_CardR__fPosI__33BFA6FF default (0),
   fDoorID              tinyint              not null constraint DF__T_E_CardR__fDoor__34B3CB38 default (0),
   fDoorCode            varchar(7)           collate Chinese_PRC_CI_AS null,
   fReaderType          tinyint              not null constraint DF__T_E_CardR__fRead__35A7EF71 default (1),
   fReaderClass         tinyint              not null constraint DF__T_E_CardR__fRead__369C13AA default (0)
)
on "PRIMARY"
go

alter table dbo.T_E_CardReader
   add constraint PK_T_E_CardReader primary key (fKeyID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_E_CheckTimes                                        */
/*==============================================================*/
create table dbo.T_E_CheckTimes (
   fKeyID               int                  identity(1, 1),
   fPosID               int                  not null,
   fTimeBH1             int                  not null constraint DF__T_E_Check__fTime__379037E3 default (0),
   fTimeBS1             int                  not null constraint DF__T_E_Check__fTime__38845C1C default (0),
   fTimeEH1             int                  not null constraint DF__T_E_Check__fTime__39788055 default (0),
   fTimeES1             int                  not null constraint DF__T_E_Check__fTime__3A6CA48E default (0),
   fTimeBH2             int                  not null constraint DF__T_E_Check__fTime__3B60C8C7 default (0),
   fTimeBS2             int                  not null constraint DF__T_E_Check__fTime__3C54ED00 default (0),
   fTimeEH2             int                  not null constraint DF__T_E_Check__fTime__3D491139 default (0),
   fTimeES2             int                  not null constraint DF__T_E_Check__fTime__3E3D3572 default (0),
   fTimeBH3             int                  not null constraint DF__T_E_Check__fTime__3F3159AB default (0),
   fTimeBS3             int                  not null constraint DF__T_E_Check__fTime__40257DE4 default (0),
   fTimeEH3             int                  not null constraint DF__T_E_Check__fTime__4119A21D default (0),
   fTimeES3             int                  not null constraint DF__T_E_Check__fTime__420DC656 default (0),
   fTimeBH4             int                  not null constraint DF__T_E_Check__fTime__4301EA8F default (0),
   fTimeBS4             int                  not null constraint DF__T_E_Check__fTime__43F60EC8 default (0),
   fTimeEH4             int                  not null constraint DF__T_E_Check__fTime__44EA3301 default (0),
   fTimeES4             int                  not null constraint DF__T_E_Check__fTime__45DE573A default (0),
   fTimeBH5             int                  not null constraint DF__T_E_Check__fTime__46D27B73 default (0),
   fTimeBS5             int                  not null constraint DF__T_E_Check__fTime__47C69FAC default (0),
   fTimeEH5             int                  not null constraint DF__T_E_Check__fTime__48BAC3E5 default (0),
   fTimeES5             int                  not null constraint DF__T_E_Check__fTime__49AEE81E default (0),
   fTimeBH6             int                  not null constraint DF__T_E_Check__fTime__4AA30C57 default (0),
   fTimeBS6             int                  not null constraint DF__T_E_Check__fTime__4B973090 default (0),
   fTimeEH6             int                  not null constraint DF__T_E_Check__fTime__4C8B54C9 default (0),
   fTimeES6             int                  not null constraint DF__T_E_Check__fTime__4D7F7902 default (0)
)
on "PRIMARY"
go

alter table dbo.T_E_CheckTimes
   add constraint PK_T_E_CheckTimes primary key (fKeyID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_E_CtrlRule                                          */
/*==============================================================*/
create table dbo.T_E_CtrlRule (
   fPosID               int                  not null,
   fCtrlRuleID          smallint             not null,
   fEnable              bit                  not null constraint DF__T_E_CtrlR__fEnab__4E739D3B default (0),
   fDoor1Rule           int                  not null constraint DF__T_E_CtrlR__fDoor__4F67C174 default (0),
   fDoor2Rule           int                  not null constraint DF__T_E_CtrlR__fDoor__505BE5AD default (0),
   fDoor3Rule           int                  not null constraint DF__T_E_CtrlR__fDoor__515009E6 default (0),
   fDoor4Rule           int                  not null constraint DF__T_E_CtrlR__fDoor__52442E1F default (0)
)
on "PRIMARY"
go

alter table dbo.T_E_CtrlRule
   add constraint PK_T_E_CtrlRule primary key (fPosID, fCtrlRuleID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_E_Door                                              */
/*==============================================================*/
create table dbo.T_E_Door (
   fKeyID               int                  identity(1, 1),
   fDoorID              int                  not null constraint DF__T_E_Door__fDoorI__53385258 default (0),
   fDoorName            varchar(64)          collate Chinese_PRC_CI_AS not null,
   fDoorCode            varchar(7)           collate Chinese_PRC_CI_AS null,
   fPosID               int                  not null,
   fOpenTime            int                  not null constraint DF__T_E_Door__fOpenT__542C7691 default (1),
   fClosureTimeLapse    tinyint              not null constraint DF__T_E_Door__fClosu__55209ACA default (1),
   fWarnEvent           int                  null constraint DF__T_E_Door__fWarnE__5614BF03 default (0),
   fWarnTime            int                  null constraint DF__T_E_Door__fWarnT__5708E33C default (1),
   fWarnExport          int                  null constraint DF__T_E_Door__fWarnE__57FD0775 default (0),
   fDoorPsd             varchar(8)           collate Chinese_PRC_CI_AS null constraint DF__T_E_Door__fDoorP__58F12BAE default (0),
   fDoorState           tinyint              null constraint DF__T_E_Door__fDoorS__59E54FE7 default (0),
   fControlType         int                  null constraint DF__T_E_Door__fContr__5AD97420 default (0),
   fBtnEnable           tinyint              null constraint DF__T_E_Door__fBtnEn__5BCD9859 default (0)
)
on "PRIMARY"
go

alter table dbo.T_E_Door
   add constraint PK_T_E_Door primary key (fKeyID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_E_DoorRule                                          */
/*==============================================================*/
create table dbo.T_E_DoorRule (
   fKeyID               int                  identity(1, 1),
   fPosId               int                  not null,
   fDoorCode            varchar(7)           collate Chinese_PRC_CI_AS not null,
   fDoorID              int                  not null,
   fDPRuleID            smallint             not null,
   fStartTime           varchar(5)           collate Chinese_PRC_CI_AS not null constraint DF__T_E_DoorR__fStar__5CC1BC92 default '00:00',
   fEndTime             varchar(5)           collate Chinese_PRC_CI_AS not null constraint DF__T_E_DoorR__fEndT__5DB5E0CB default '23:59',
   fWeekValid           int                  not null constraint DF__T_E_DoorR__fWeek__5EAA0504 default (0),
   fSecernClass         int                  not null constraint DF__T_E_DoorR__fSece__5F9E293D default (0)
)
on "PRIMARY"
go

alter table dbo.T_E_DoorRule
   add constraint PK_T_E_DoorRule primary key (fKeyID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_E_EmpRule                                           */
/*==============================================================*/
create table dbo.T_E_EmpRule (
   fKeyID               int                  identity(1, 1),
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS not null,
   fEnable              bit                  not null constraint DF__T_E_EmpRu__fEnab__60924D76 default (1),
   fPosID               int                  not null,
   fCtrlRuleID          int                  not null,
   fPass                varchar(6)           collate Chinese_PRC_CI_AS null constraint DF__T_E_EmpRu__fPass__618671AF default (0),
   fDoor1Rule           int                  not null constraint DF__T_E_EmpRu__fDoor__627A95E8 default (0),
   fDoor2Rule           int                  not null constraint DF__T_E_EmpRu__fDoor__636EBA21 default (0),
   fDoor3Rule           int                  not null constraint DF__T_E_EmpRu__fDoor__6462DE5A default (0),
   fDoor4Rule           int                  not null constraint DF__T_E_EmpRu__fDoor__65570293 default (0),
   fXGEnable            bit                  not null constraint DF__T_E_EmpRu__fXGEn__664B26CC default (0),
   fDeadLine            datetime             not null constraint DF__T_E_EmpRu__fDead__673F4B05 default getdate()
)
on "PRIMARY"
go

alter table dbo.T_E_EmpRule
   add constraint PK_T_C_EmplyeeRule primary key (fKeyID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_E_EmpRuleCust                                       */
/*==============================================================*/
create table dbo.T_E_EmpRuleCust (
   fKeyID               int                  identity(1, 1),
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS null,
   fCtrlRuleID          int                  null,
   fPass                varchar(6)           collate Chinese_PRC_CI_AS null,
   fDeadLine            datetime             null
)
on "PRIMARY"
go

alter table dbo.T_E_EmpRuleCust
   add constraint PK__T_E_EmpR__23D5CF662D1D9668 primary key (fKeyID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_E_EmpRuleHistory                                    */
/*==============================================================*/
create table dbo.T_E_EmpRuleHistory (
   fKeyID               int                  identity(1, 1),
   fGroupID             varchar(20)          collate Chinese_PRC_CI_AS null,
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS null,
   fPhysicalNo          varchar(30)          collate Chinese_PRC_CI_AS null,
   fPosID               int                  null,
   fCtrlRuleID          int                  null,
   fDoor1Rule           int                  null,
   fDoor2Rule           int                  null,
   fDoor3Rule           int                  null,
   fDoor4Rule           int                  null,
   fOperID              varchar(40)          collate Chinese_PRC_CI_AS null,
   fOperateTime         datetime             null constraint DF__T_E_EmpRu__fOper__68336F3E default getdate(),
   fRemark              varchar(100)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_E_EmpRuleHistory
   add constraint PK__T_E_EmpR__23D5CF6630EE274C primary key (fKeyID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_E_ErrType                                           */
/*==============================================================*/
create table dbo.T_E_ErrType (
   fTypeID              int                  not null,
   fTypeName            varchar(50)          collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_E_ErrorRec                                          */
/*==============================================================*/
create table dbo.T_E_ErrorRec (
   fKeyID               int                  identity(1, 1),
   fPosID               int                  not null,
   fErrorCode           int                  not null,
   fErrorExplain        varchar(100)         collate Chinese_PRC_CI_AS null,
   fErrorTime           datetime             not null constraint DF__T_E_Error__fErro__69279377 default getdate()
)
on "PRIMARY"
go

alter table dbo.T_E_ErrorRec
   add constraint PK_T_E_ErrorRec primary key (fKeyID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_E_PassRule                                          */
/*==============================================================*/
create table dbo.T_E_PassRule (
   fCtrlRuleID          int                  not null,
   fCtrlRuleName        varchar(60)          collate Chinese_PRC_CI_AS null,
   fEnable              bit                  not null constraint DF__T_E_PassR__fEnab__6A1BB7B0 default (1),
   fRemark              varchar(200)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_E_PassRule
   add constraint PK_T_E_PassRule primary key (fCtrlRuleID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_E_RecType                                           */
/*==============================================================*/
create table dbo.T_E_RecType (
   fTypeID              int                  not null,
   fTypeName            varchar(50)          collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: T_L_AWhite                                            */
/*==============================================================*/
create table dbo.T_L_AWhite (
   fVer                 int                  identity(1, 1),
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS not null,
   fCardNo              varchar(20)          collate Chinese_PRC_CI_AS not null,
   fPhysicalNo          varchar(30)          collate Chinese_PRC_CI_AS null,
   fPosID               int                  not null constraint DF__T_L_AWhit__fPosI__6B0FDBE9 default (0),
   fOperType            varchar(2)           collate Chinese_PRC_CI_AS not null constraint DF__T_L_AWhit__fOper__6C040022 default 'A',
   fOperTime            datetime             not null constraint DF__T_L_AWhit__fOper__6CF8245B default getdate(),
   fIsUsed              bit                  not null constraint DF__T_L_AWhit__fIsUs__6DEC4894 default (1),
   fRemark              varchar(20)          collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_L_AWhite
   add constraint PK_T_L_AWhite primary key (fVer)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_L_CBlack                                            */
/*==============================================================*/
create table dbo.T_L_CBlack (
   fVer                 int                  identity(1, 1),
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS not null,
   fCardNo              varchar(20)          collate Chinese_PRC_CI_AS not null,
   fPhysicalNo          varchar(30)          collate Chinese_PRC_CI_AS null,
   fPosID               int                  not null constraint DF__T_L_CBlac__fPosI__6EE06CCD default (0),
   fOperType            varchar(2)           collate Chinese_PRC_CI_AS not null constraint DF__T_L_CBlac__fOper__6FD49106 default 'A',
   fOperTime            datetime             not null constraint DF__T_L_CBlac__fOper__70C8B53F default getdate(),
   fIsUsed              bit                  not null constraint DF__T_L_CBlac__fIsUs__71BCD978 default (1),
   fRemark              varchar(20)          collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_L_CBlack
   add constraint PK_T_L_CBlack primary key (fVer)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_L_CWhite                                            */
/*==============================================================*/
create table dbo.T_L_CWhite (
   fVer                 int                  identity(1, 1),
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS not null,
   fCardNo              varchar(20)          collate Chinese_PRC_CI_AS not null,
   fPhysicalNo          varchar(30)          collate Chinese_PRC_CI_AS null,
   fPosID               int                  not null constraint DF__T_L_CWhit__fPosI__72B0FDB1 default (0),
   fOperType            varchar(2)           collate Chinese_PRC_CI_AS not null constraint DF__T_L_CWhit__fOper__73A521EA default 'A',
   fOperTime            datetime             not null constraint DF__T_L_CWhit__fOper__74994623 default getdate(),
   fIsUsed              bit                  not null constraint DF__T_L_CWhit__fIsUs__758D6A5C default (1),
   fRemark              varchar(20)          collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_L_CWhite
   add constraint PK_T_L_CWhite primary key (fVer)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_L_EWhite                                            */
/*==============================================================*/
create table dbo.T_L_EWhite (
   fVer                 int                  identity(1, 1),
   fAccountID           varchar(18)          collate Chinese_PRC_CI_AS not null,
   fCardNo              varchar(20)          collate Chinese_PRC_CI_AS not null,
   fPhysicalNo          varchar(30)          collate Chinese_PRC_CI_AS null,
   fPosID               int                  not null constraint DF__T_L_EWhit__fPosI__76818E95 default (0),
   fOperType            varchar(2)           collate Chinese_PRC_CI_AS not null constraint DF__T_L_EWhit__fOper__7775B2CE default 'A',
   fOperTime            datetime             not null constraint DF__T_L_EWhit__fOper__7869D707 default getdate(),
   fIsUsed              bit                  not null constraint DF__T_L_EWhit__fIsUs__795DFB40 default (1),
   fRemark              varchar(20)          collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_L_EWhite
   add constraint PK_T_L_EWhite primary key (fVer)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_Payment                                             */
/*==============================================================*/
create table dbo.T_Payment (
   fOrderWater          int                  identity(1, 10000),
   fPosID               int                  not null constraint DF__T_Payment__fPosI__00DF2177 default (0),
   fPayType             int                  not null constraint DF__T_Payment__fPayT__01D345B0 default (0),
   fRequestTime         datetime             not null,
   fPayMoney            money                not null,
   fRequestJson         varchar(500)         collate Chinese_PRC_CI_AS null,
   fStatus              int                  not null,
   fResponseTime        datetime             null,
   fMsgCode             varchar(10)          collate Chinese_PRC_CI_AS null,
   fMsgInfo             varchar(100)         collate Chinese_PRC_CI_AS null,
   fResult              int                  null,
   fCodeURL             varchar(100)         collate Chinese_PRC_CI_AS null,
   fPrepayID            varchar(20)          collate Chinese_PRC_CI_AS null,
   fAppID               varchar(20)          collate Chinese_PRC_CI_AS null,
   fPartnerid           varchar(20)          collate Chinese_PRC_CI_AS null,
   outTradeNo           varchar(64)          collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_Payment
   add constraint PK_T_Payment_1 primary key (fOrderWater)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_R_Dict                                              */
/*==============================================================*/
create table dbo.T_R_Dict (
   fDictID              int                  identity(1, 1),
   fDictType            int                  null,
   fDictName            varchar(40)          collate Chinese_PRC_CI_AS null,
   fSerialNO            int                  null,
   fDisplayName         varchar(40)          collate Chinese_PRC_CI_AS null,
   fFootType            int                  not null,
   fDictContent         varchar(100)         collate Chinese_PRC_CI_AS null,
   fMask                varchar(40)          collate Chinese_PRC_CI_AS null,
   fMax                 varchar(50)          collate Chinese_PRC_CI_AS null,
   fMin                 varchar(50)          collate Chinese_PRC_CI_AS null,
   fDictDefault         varchar(50)          collate Chinese_PRC_CI_AS null,
   fIsCheck             bit                  null,
   fIsPrint             bit                  null,
   fIsScript            bit                  null,
   fReportID            int                  null,
   fRemark              varchar(100)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_R_Dict
   add constraint PK_T_R_Dict primary key (fDictID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_R_DictRela                                          */
/*==============================================================*/
create table dbo.T_R_DictRela (
   fID                  int                  identity(1, 1),
   fRelaID              int                  not null,
   fSouDictID           int                  not null,
   fDesDictID           int                  not null,
   fMark                varchar(50)          collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_R_DictRela
   add constraint PK_T_R_DictRela primary key (fID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_R_Group                                             */
/*==============================================================*/
create table dbo.T_R_Group (
   fRSGroupID           int                  identity(1, 1),
   fRSGroupCode         varchar(20)          collate Chinese_PRC_CI_AS not null,
   fRSGroupName         varchar(40)          collate Chinese_PRC_CI_AS not null,
   fRSGroupLevel        int                  not null,
   fRSRemark            varchar(100)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_R_Group
   add constraint PK_T_R_Group primary key (fRSGroupID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_R_Manager                                           */
/*==============================================================*/
create table dbo.T_R_Manager (
   fOperID              int                  identity(1, 1),
   fLoginName           varchar(40)          collate Chinese_PRC_CI_AS not null,
   fRealName            varchar(40)          collate Chinese_PRC_CI_AS not null,
   fPassword            varchar(40)          collate Chinese_PRC_CI_AS null,
   fRight               varchar(400)         collate Chinese_PRC_CI_AS null,
   fRemark              varchar(200)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_R_Manager
   add constraint PK_T_R_Manager primary key (fOperID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_R_Report                                            */
/*==============================================================*/
create table dbo.T_R_Report (
   fReportID            int                  not null,
   fReportName          varchar(40)          collate Chinese_PRC_CI_AS null,
   fReportProc          varchar(60)          collate Chinese_PRC_CI_AS null,
   fReportType          int                  null,
   fGroupID             varchar(25)          collate Chinese_PRC_CI_AS null,
   ffr3fileName         varchar(50)          collate Chinese_PRC_CI_AS null,
   fDisPlay             int                  null,
   fDefaultDis          int                  null,
   fPrintDirection      bit                  null,
   fColUnDis            varchar(20)          collate Chinese_PRC_CI_AS null,
   fColFix              int                  null,
   fTotleDis            varchar(1000)        collate Chinese_PRC_CI_AS null,
   fHide                bit                  null,
   fBPageDis            bit                  null constraint DF__T_R_Repor__fBPag__2CDD9F46 default (0),
   fRemark              varchar(200)         collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.T_R_Report
   add constraint PK_T_R_Report primary key (fReportID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_R_ReportRela                                        */
/*==============================================================*/
create table dbo.T_R_ReportRela (
   fID                  int                  identity(1, 1),
   fRelaID              int                  not null,
   fReportParentID      int                  not null,
   fReportChildID       int                  not null,
   fIsDisPlay           bit                  not null
)
on "PRIMARY"
go

alter table dbo.T_R_ReportRela
   add constraint PK_T_R_ReportRela primary key (fID)
      on "PRIMARY"
go

/*==============================================================*/
/* Table: T_R_SysAccount                                        */
/*==============================================================*/
create table dbo.T_R_SysAccount (
   id                   bigint               identity(1, 1),
   OperDate             datetime             not null,
   Acount               bigint               not null constraint DF__T_R_SysAc__Acoun__7B4643B2 default (0),
   AcountMoney          money         not null constraint DF__T_R_SysAc__Acoun__7C3A67EB default (0),
   ConsCount            bigint               not null constraint DF__T_R_SysAc__ConsC__7D2E8C24 default (0),
   ConsMoney            money         not null constraint DF__T_R_SysAc__ConsM__7E22B05D default (0),
   khCount              int                  null,
   KhtlSum              money         not null constraint DF__T_R_SysAc__KhtlS__7F16D496 default (0),
   KhDpsit              money         not null constraint DF__T_R_SysAc__KhDps__000AF8CF default (0),
   KhPndge              money         not null constraint DF__T_R_SysAc__KhPnd__00FF1D08 default (0),
   KhManage             money         not null constraint DF__T_R_SysAc__KhMan__01F34141 default (0),
   ChCount              int                  not null constraint DF__T_R_SysAc__ChCou__02E7657A default (0),
   ChtlSum              money         not null constraint DF__T_R_SysAc__ChtlS__03DB89B3 default (0),
   ChMoney              money         not null constraint DF__T_R_SysAc__ChMon__04CFADEC default (0),
   ChPndge              money         not null constraint DF__T_R_SysAc__ChPnd__05C3D225 default (0),
   GsCount              int                  not null constraint DF__T_R_SysAc__GsCou__06B7F65E default (0),
   GsPndge              money         not null constraint DF__T_R_SysAc__GsPnd__07AC1A97 default (0),
   JgCount              int                  not null constraint DF__T_R_SysAc__JgCou__08A03ED0 default (0),
   JgPndge              money         not null constraint DF__T_R_SysAc__JgPnd__09946309 default (0),
   SvCount              int                  not null constraint DF__T_R_SysAc__SvCou__0A888742 default (0),
   SvPndge              money         not null constraint DF__T_R_SysAc__SvPnd__0B7CAB7B default (0),
   SvtlSum              money         not null constraint DF__T_R_SysAc__SvtlS__0C70CFB4 default (0),
   TkCount              int                  not null constraint DF__T_R_SysAc__TkCou__0D64F3ED default (0),
   TktlSum              money         not null constraint DF__T_R_SysAc__TktlS__0E591826 default (0),
   HkCount              int                  not null constraint DF__T_R_SysAc__HkCou__0F4D3C5F default (0),
   HkPndge              money         not null constraint DF__T_R_SysAc__HkPnd__10416098 default (0),
   BkCount              int                  not null constraint DF__T_R_SysAc__BkCou__113584D1 default (0),
   BktlSum              money         not null constraint DF__T_R_SysAc__BktlS__1229A90A default (0),
   BkPndge              money         not null constraint DF__T_R_SysAc__BkPnd__131DCD43 default (0),
   JcCount              int                  not null constraint DF__T_R_SysAc__JcCou__1411F17C default (0),
   JctlSum              money         not null constraint DF__T_R_SysAc__JctlS__150615B5 default (0),
   SbCount              int                  not null constraint DF__T_R_SysAc__SbCou__15FA39EE default (0),
   SbtlSum              money         not null constraint DF__T_R_SysAc__SbtlS__16EE5E27 default (0),
   sbClearCount         int                  not null constraint DF__T_R_SysAc__sbCle__17E28260 default (0),
   sbClearSum           money         not null constraint DF__T_R_SysAc__sbCle__18D6A699 default (0),
   QCCount              int                  not null constraint DF__T_R_SysAc__QCCou__19CACAD2 default (0),
   QCtlSum              money         not null constraint DF__T_R_SysAc__QCtlS__1ABEEF0B default (0),
   QCBXCount            int                  not null constraint DF__T_R_SysAc__QCBXC__1BB31344 default (0),
   QCBXtlSum            money         not null constraint DF__T_R_SysAc__QCBXt__1CA7377D default (0),
   qtsr                 money         not null constraint DF__T_R_SysAcc__qtsr__1D9B5BB6 default (0)
)
on "PRIMARY"
go

/*==============================================================*/
/* Table: tb_yzf_record                                         */
/*==============================================================*/
create table dbo.tb_yzf_record (
   orderId              varchar(50)          collate Chinese_PRC_CI_AS not null,
   orderSeq             varchar(50)          collate Chinese_PRC_CI_AS null,
   tranSeq              varchar(50)          collate Chinese_PRC_CI_AS null,
   merchantId           varchar(50)          collate Chinese_PRC_CI_AS null,
   phoneNumber          varchar(50)          collate Chinese_PRC_CI_AS null,
   iccid                varchar(50)          collate Chinese_PRC_CI_AS null,
   NAME                 varchar(50)          collate Chinese_PRC_CI_AS null,
   amount               varchar(50)          collate Chinese_PRC_CI_AS null,
   orderDate            varchar(50)          collate Chinese_PRC_CI_AS null,
   clientId             varchar(50)          collate Chinese_PRC_CI_AS null,
   versionId            varchar(50)          collate Chinese_PRC_CI_AS null,
   createDate           datetime             null,
   joinDesc             varchar(50)          collate Chinese_PRC_CI_AS null,
   flag                 int                  null,
   dealTime             varchar(50)          collate Chinese_PRC_CI_AS null,
   RESULT               varchar(50)          collate Chinese_PRC_CI_AS null
)
on "PRIMARY"
go

alter table dbo.tb_yzf_record
   add constraint PK__tb_yzf_r__0809335D76818E95 primary key (orderId)
      on "PRIMARY"
go


/*==============================================================*/
/* Table: T_R_SysAccount_Month                                  */
/*==============================================================*/
	CREATE TABLE [dbo].[T_R_SysAccount_Month](
		[fID] [bigint] IDENTITY(1, 1) NOT NULL,
		[fDataYM] [varchar](7) NOT NULL,
		[fDataBDate] [datetime] NOT NULL,
		[fDataEDate] [datetime] NOT NULL,
		[fConsCount] [bigint] NOT NULL DEFAULT (0),
		[fConsMoney] [money] NOT NULL DEFAULT (0),
		[fkhCount] [int] NOT NULL DEFAULT (0),
		[fKhMoney] [money] NOT NULL DEFAULT (0),
		[fKhDpsit] [money] NOT NULL DEFAULT (0),
		[fKhPndge] [money] NOT NULL DEFAULT (0),
		[fKhManage] [money] NOT NULL DEFAULT (0),
		[fChCount] [int] NOT NULL DEFAULT (0),
		[fChMoney] [money] NOT NULL DEFAULT (0),
		[fChDpsit] [money] NOT NULL DEFAULT (0),
		[fChPndge] [money] NOT NULL DEFAULT (0),
		[fGsCount] [int] NOT NULL DEFAULT (0),
		[fGsPndge] [money] NOT NULL DEFAULT (0),
		[fJgCount] [int] NOT NULL DEFAULT (0),
		[fJgPndge] [money] NOT NULL DEFAULT (0),
		[fSvCount] [int] NOT NULL DEFAULT (0),
		[fSvPndge] [money] NOT NULL DEFAULT (0),
		[fSvMoney] [money] NOT NULL DEFAULT (0),
		[fTkCount] [int] NOT NULL DEFAULT (0),
		[fTkMoney] [money] NOT NULL DEFAULT (0),
		[fHkCount] [int] NOT NULL DEFAULT (0),
		[fHkPndge] [money] NOT NULL DEFAULT (0),
		[fBkCount] [int] NOT NULL DEFAULT (0),
		[fBkMoney] [money] NOT NULL DEFAULT (0),
		[fBkPndge] [money] NOT NULL DEFAULT (0),
		[fJcCount] [int] NOT NULL DEFAULT (0),
		[fJcMoney] [money] NOT NULL DEFAULT (0),
		[fSbCount] [int] NOT NULL DEFAULT (0),
		[fSbMoney] [money] NOT NULL DEFAULT (0),
		[fsbClrCount] [int] NOT NULL DEFAULT (0),
		[fsbClrMoney] [money] NOT NULL DEFAULT (0),
		[fQCCount] [int] NOT NULL DEFAULT (0),
		[fQCMoney] [money] NOT NULL DEFAULT (0),
		[fQCBXCount] [int] NOT NULL DEFAULT (0),
		[fQCBXMoney] [money] NOT NULL DEFAULT (0),
		[fAccountCount] [bigint] NOT NULL DEFAULT (0),
		[fAccountBalance] [money] NOT NULL DEFAULT (0),

		[fConsMoneyJC] [int] NOT NULL DEFAULT (0),
		[fSbCountJC] [int] NOT NULL DEFAULT (0),
		[fSbMoneyJC] [int] NOT NULL DEFAULT (0),
		[fSbClrCountJC] [int] NOT NULL DEFAULT (0),
		[fSbClrMoneyJC] [int] NOT NULL DEFAULT (0),
		[fJcCountJC] [int] NOT NULL DEFAULT (0),
		[fJcMoneyJC] [int] NOT NULL DEFAULT (0),
		[fSvCountJC] [int] NOT NULL DEFAULT (0),
		[fSvMoneyJC] [int] NOT NULL DEFAULT (0),
		[fTkCountJC] [int] NOT NULL DEFAULT (0),
		[fTkMoneyJC] [int] NOT NULL DEFAULT (0),
		[fAccountBalanceJC] [int] NOT NULL DEFAULT (0),
		[fAccountDate] [datetime] NOT NULL DEFAULT getdate()
	) ON [PRIMARY]
GO

/*==============================================================*/
/* Table: T_C_SumEmpDealByMonth                                  */
/*==============================================================*/
CREATE TABLE [dbo].[T_C_SumEmpDealByMonth](
	[fKeyID] [int] IDENTITY(1,1) NOT NULL,
	[fDate] [varchar](7) NOT NULL,
	[fCreateTime] [datetime] NULL DEFAULT getdate(),
	[fOpreID] [int] NULL
) ON [PRIMARY]


/*==============================================================*/
/* View: V_A_ReportDay                                          */
/*==============================================================*/
create view dbo.V_A_ReportDay as
SELECT dbo.T_A_ReportDays.fAccountID AS 账号, dbo.T_B_Employee.fName AS 姓名, 
      dbo.T_B_Employee.fSerialNo AS 卡号, dbo.T_B_Employee.fEmployeeCode AS 工号, 
      dbo.T_A_WorkTime.fWorkTimeName AS 班次, 
      dbo.T_A_ReportDays.fCheckDate AS 考勤日期, 
      dbo.T_A_ReportDays.fWeekday AS 星期, 
      replace(dbo.T_A_ReportDays.fOnDuty1,'00:00','') AS 签到时间一, 
      replace(dbo.T_A_ReportDays.fOffDuty1,'00:00','') AS 签退时间一, 
       replace(dbo.T_A_ReportDays.fOnDuty2,'00:00','') AS 签到时间二, 
       replace(dbo.T_A_ReportDays.fOffDuty2,'00:00','') AS 签退时间二, 
       replace(dbo.T_A_ReportDays.fOnDuty3,'00:00','') AS 签到时间三, 
       replace(dbo.T_A_ReportDays.fOffDuty3,'00:00','') AS 签退时间三, 
       replace(dbo.T_A_ReportDays.fOnDuty4,'00:00','') AS 签到时间四, 
       replace(dbo.T_A_ReportDays.fOffDuty4,'00:00','') AS 签退时间四, 
       replace(dbo.T_A_ReportDays.fOnDuty5,'00:00','') AS 签到时间五, 
       replace(dbo.T_A_ReportDays.fOffDuty5,'00:00','') AS 签退时间五, 
       replace(dbo.T_A_ReportDays.fOnDuty6,'00:00','') AS 签到时间六, 
       replace(dbo.T_A_ReportDays.fOffDuty6,'00:00','') AS 签退时间六, 
      dbo.T_A_ReportDays.fManHour AS 工时, 
      dbo.T_A_ReportDays.fOverdueCount AS 迟到次数, 
      dbo.T_A_ReportDays.fOverdueMinutes AS 迟到分钟, 
      dbo.T_A_ReportDays.fEarlyCount AS 早退次数, 
      dbo.T_A_ReportDays.fEarlyMinutes AS 早退分钟, 
      dbo.T_A_ReportDays.fAbsentDays AS 旷工天数, 
      dbo.T_A_ReportDays.fAbsentMinutes AS 旷工分钟, 
      dbo.T_A_ReportDays.fLeaveDays AS 请假天数, 
      dbo.T_A_ReportDays.fLeaveMinutes AS 请假分钟, 
      dbo.T_A_ReportDays.fEvectionDays AS 出差天数, 
      dbo.T_A_ReportDays.fEvectionMinutes AS 出差分钟, 
      dbo.T_A_ReportDays.fOvertimeMinutes AS 加班分钟, 
      dbo.T_A_ReportDays.fExplain AS 说明
FROM dbo.T_A_ReportDays INNER JOIN
      dbo.T_B_Employee ON 
      dbo.T_A_ReportDays.fAccountID = dbo.T_B_Employee.fAccountID INNER JOIN
      dbo.T_B_Dept ON dbo.T_B_Employee.fDept = dbo.T_B_Dept.fDeptCode left JOIN
      dbo.T_A_WorkTime ON 
      dbo.T_A_ReportDays.fWorkTimeCode = dbo.T_A_WorkTime.fWorkTimeCode
go

/*==============================================================*/
/* View: V_A_ReportMonth                                        */
/*==============================================================*/
create view dbo.V_A_ReportMonth as
SELECT dbo.T_B_Employee.fName AS 姓名, dbo.T_B_Employee.fSerialNo AS 卡号, 
      dbo.T_B_Dept.fDeptName AS 部门, dbo.T_A_ReportMonths.fAccountID AS 账号, 
      dbo.T_A_ReportMonths.fYear AS 年份, dbo.T_A_ReportMonths.fMonth AS 月份, 
      dbo.T_A_ReportMonths.fOughtDays AS 应出勤天数, 
      dbo.T_A_ReportMonths.fFactDays AS 实出勤天数, 
      dbo.T_A_ReportMonths.fOverdueCount AS 迟到次数, 
      dbo.T_A_ReportMonths.fOverdueMinutes AS 迟到分钟, 
      dbo.T_A_ReportMonths.fEarlyCount AS 早退次数, 
      dbo.T_A_ReportMonths.fEarlyMinutes AS 早退分钟, 
      dbo.T_A_ReportMonths.fAbsentDays AS 旷工天数, 
      dbo.T_A_ReportMonths.fAbsentMinutes AS 旷工分钟, 
      dbo.T_A_ReportMonths.fLeaveDays AS 请假天数, 
      dbo.T_A_ReportMonths.fLeaveMinutes AS 请假分钟, 
      dbo.T_A_ReportMonths.fEvectionDays AS 出差天数, 
      dbo.T_A_ReportMonths.fEvectionMinutes AS 出差分钟, 
      dbo.T_A_ReportMonths.fOvertimeMinutes AS 加班分钟, 
      dbo.T_A_ReportMonths.fManhour AS 工时
FROM dbo.T_A_ReportMonths INNER JOIN
      dbo.T_B_Employee ON 
      dbo.T_A_ReportMonths.fAccountID = dbo.T_B_Employee.fAccountID INNER JOIN
      dbo.T_B_Dept ON dbo.T_B_Employee.fDept = dbo.T_B_Dept.fDeptCode
go

/*==============================================================*/
/* View: V_B_ActDetail                                          */
/*==============================================================*/
create view dbo.V_B_ActDetail as
SELECT dbo.T_B_Employee.fName AS 姓名, 
      dbo.T_B_Employee.fAccountID AS 账号, 
      dbo.T_B_Employee.fEmployeeCode AS 学工号,
       dbo.T_B_Employee.fSerialNo AS 卡号, 
      dbo.T_B_Dept.fDeptName AS 部门, 
      CASE WHEN dbo.T_B_Employee.fSex=0 THEN '女' ELSE '男' END AS 性别, 
      dbo.T_B_ManType.fId_TypeName AS 身份类型, 
      CASE WHEN dbo.T_B_Employee.fCard_State=0 THEN '正常' 
	   WHEN dbo.T_B_Employee.fCard_State=1 THEN '挂失'
	   WHEN dbo.T_B_Employee.fCard_State=2 THEN '销卡' 
	   WHEN dbo.T_B_Employee.fCard_State=3 THEN '未发卡'
	   WHEN dbo.T_B_Employee.fCard_State=4 THEN '撤户' END AS 卡状态, 
      dbo.T_B_Employee.fBalanceMon AS 现金余额, 
      dbo.T_B_Employee.fBalanceSub AS 补助余额
FROM dbo.T_B_Employee INNER JOIN
      dbo.T_B_ManType ON 
      dbo.T_B_Employee.fId_TypeId = dbo.T_B_ManType.fId_TypeId INNER JOIN
      dbo.T_B_Dept ON dbo.T_B_Employee.fDept = dbo.T_B_Dept.fDeptCode
go

/*==============================================================*/
/* View: V_B_AtdPos                                             */
/*==============================================================*/
create view dbo.V_B_AtdPos  as
select
   fPosID,
   fPosName,
   fPosType,
   fPosClass,
   fPosPwd,
   fCom,
   fConnType,
   fState,
   fSiteID,
   fIpAddr,
   fTcpPort,
   fServerIp,
   fIssuer,
   fPosVersion,
   fMJType,
   fDoorLock,
   fWarnTime,
   fFireAlarmTime,
   fHintTime,
   fWarnExport,
   fFireWarnExport,
   fSuperPsd,
   fBasePsd,
   fIntimidatePwd,
   fFireWarnOpen,
   fWarnOpen,
   fRecDisposal,
   fSN,
   fIpMask,
   fGetWay,
   fServerMac,
   fGetWayMac,
   fPosMac,
   fConsGroup,
   fRate,
   fTimeUnit,
   dbo.FN_GetPosType(fPosType) as fPosTypeName
from
   dbo.T_B_Pos
where
   fPosType = 0
   or fPosType = 9
go

/*==============================================================*/
/* View: V_B_Cards                                              */
/*==============================================================*/
create view dbo.V_B_Cards as
SELECT     dbo.T_B_Cards.fAccountID, dbo.T_B_Cards.fSerialID, dbo.T_B_CardType.fCardTypeName, dbo.T_B_Cards.fCardTypeID, dbo.T_B_Cards.fSerialNo, 
                      dbo.T_B_Cards.fCardTransNo, dbo.T_B_Cards.fCardState, dbo.T_B_Cards.fCardBatchID, dbo.T_B_Cards.fCreateDate, dbo.T_B_Cards.fLimitDate, 
                      dbo.T_B_Cards.fDeleteDate, dbo.T_B_Cards.fCardDeposit, dbo.T_B_CardType.fIsMainCard, dbo.T_B_CardType.fCardType, dbo.T_B_CardType.fState, 
                      dbo.T_B_CardType.fDeposit
FROM         dbo.T_B_Cards INNER JOIN
                      dbo.T_B_CardType ON dbo.T_B_Cards.fCardTypeID = dbo.T_B_CardType.fCardTypeID
go

/*==============================================================*/
/* View: V_B_ConsPos                                            */
/*==============================================================*/
create view dbo.V_B_ConsPos as
select
   fPosID,
   fPosName,
   fPosType,
   fPosClass,
   fPosPwd,
   fCom,
   fConnType,
   fState,
   fSiteID,
   fIpAddr,
   fTcpPort,
   fServerIp,
   fIssuer,
   fPosVersion,
   fMJType,
   fDoorLock,
   fWarnTime,
   fFireAlarmTime,
   fHintTime,
   fWarnExport,
   fFireWarnExport,
   fSuperPsd,
   fBasePsd,
   fIntimidatePwd,
   fFireWarnOpen,
   fWarnOpen,
   fRecDisposal,
   fSN,
   fIpMask,
   fGetWay,
   fServerMac,
   fGetWayMac,
   fPosMac,
   fConsGroup,
   fRate,
   fTimeUnit,
   dbo.FN_GetPosType(fPosType) as fPosTypeName
from
   dbo.T_B_Pos
where
   fPosType = 1
go

/*==============================================================*/
/* View: V_B_EGS_Employees                                      */
/*==============================================================*/
create view dbo.V_B_EGS_Employees as
SELECT  dbo.T_B_Dept.fDeptName, 
      dbo.T_B_Job.fJobName,dbo.T_B_Employee.*
FROM dbo.T_B_Employee INNER JOIN
      dbo.T_B_Dept ON dbo.T_B_Employee.fDept = dbo.T_B_Dept.fDeptCode INNER JOIN
      dbo.T_B_Job ON dbo.T_B_Employee.fJob = dbo.T_B_Job.fJobCode
go

/*==============================================================*/
/* View: V_B_EgsPos                                             */
/*==============================================================*/
create view dbo.V_B_EgsPos as
select
   fPosID,
   fPosName,
   fPosType,
   fPosClass,
   fPosPwd,
   fCom,
   fConnType,
   fState,
   fSiteID,
   fIpAddr,
   fTcpPort,
   fServerIp,
   fIssuer,
   fPosVersion,
   fMJType,
   fDoorLock,
   fWarnTime,
   fFireAlarmTime,
   fHintTime,
   fWarnExport,
   fFireWarnExport,
   fSuperPsd,
   fBasePsd,
   fIntimidatePwd,
   fFireWarnOpen,
   fWarnOpen,
   fRecDisposal,
   fSN,
   fIpMask,
   fGetWay,
   fServerMac,
   fGetWayMac,
   fPosMac,
   fConsGroup,
   fRate,
   fTimeUnit,
   dbo.FN_GetPosType(fPosType) as fPosTypeName
from
   dbo.T_B_Pos
where
   (fPosType = 2)
go

/*==============================================================*/
/* View: V_B_Employee                                           */
/*==============================================================*/
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

/*==============================================================*/
/* View: V_B_EvectionRec                                        */
/*==============================================================*/
create view dbo.V_B_EvectionRec as
SELECT dbo.T_B_EvectionRec.*, dbo.T_B_Employee.fName,dbo.T_B_Employee.fEmployeeCode,dbo.T_B_Dept.fDeptName
FROM dbo.T_B_EvectionRec INNER JOIN
      dbo.T_B_Employee ON 
      dbo.T_B_EvectionRec.fAccountID = dbo.T_B_Employee.fAccountID
      
        LEFT  JOIN T_B_Dept ON  dbo.T_B_Employee.fDept=T_B_Dept.FDEPTCODE
go

/*==============================================================*/
/* View: V_B_EvectionReclist                                    */
/*==============================================================*/
create view dbo.V_B_EvectionReclist as
SELECT L.*, E.fName,D.fDeptName,E.fEmployeeCode
   FROM dbo.T_B_EvectionReclist L left join dbo.T_B_Employee E ON L.fAccountID=E.fAccountID
                                   Left JOIN T_B_Dept D ON E.fDept = D.fDeptCode
go

/*==============================================================*/
/* View: V_B_LeaveListRec                                       */
/*==============================================================*/
create view dbo.V_B_LeaveListRec as
SELECT L.*, E.fName, LE.fLeaveName, D.fDeptName,E.fEmployeeCode
FROM dbo.T_B_LeaveRecList L Left JOIN dbo.T_B_Employee E ON L.fAccountID = E.fAccountID 
                            Left JOIN dbo.T_B_Leave LE ON L.fLeaveType = LE.fLeaveCode
                            Left JOIN T_B_Dept D ON E.fDept = D.fDeptCode
go

/*==============================================================*/
/* View: V_B_LeaveRec                                           */
/*==============================================================*/
create view dbo.V_B_LeaveRec as
SELECT dbo.T_B_LeaveRec.*, dbo.T_B_Employee.fName,dbo.T_B_Employee.fEmployeeCode ,
      dbo.T_B_Leave.fLeaveName
FROM dbo.T_B_LeaveRec INNER JOIN
      dbo.T_B_Employee ON 
      dbo.T_B_LeaveRec.fAccountID = dbo.T_B_Employee.fAccountID INNER JOIN
      dbo.T_B_Leave ON dbo.T_B_LeaveRec.fLeaveType = dbo.T_B_Leave.fLeaveCode
go

/*==============================================================*/
/* View: V_B_OvertimeRec                                        */
/*==============================================================*/
create view dbo.V_B_OvertimeRec as
SELECT a.*, b.fDeptName,b.fName,b.fEmployeeCode FROM T_B_OvertimeRec a inner join V_B_Employee b 
  on a.fAccountID=b.fAccountID
go

/*==============================================================*/
/* View: V_B_Pos                                                */
/*==============================================================*/
create view dbo.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: V_B_SitePos                                            */
/*==============================================================*/
create view dbo.V_B_SitePos as
SELECT a.fPosId, a.fPosName, a.fPosType,b.fBz_Id,c.fst_id, b.fBz_Name, b.fTc_Bl, d.fStation_Id, c.fSt_Name, d.fStation_Name
FROM dbo.T_B_Pos a LEFT OUTER JOIN
      dbo.T_B_Bzbm b ON SUBSTRING(a.fSiteID, 1, 6) = b.fBz_Id LEFT OUTER JOIN
      dbo.T_B_Stbm c ON SUBSTRING(a.fSiteID, 1, 4) = c.fSt_Id LEFT OUTER JOIN
      dbo.T_B_Station d ON SUBSTRING(a.fSiteID, 1, 2) = d.fStation_Id
go

/*==============================================================*/
/* View: V_BackupDetail                                         */
/*==============================================================*/
create view dbo.V_BackupDetail (backup_start_date, backup_finish_date, physical_device_name, backup_size, type, database_backup_lsn, checkpoint_lsn) as
SELECT TOP 100 PERCENT a.backup_start_date, a.backup_finish_date, 
      c.physical_device_name, a.backup_size, a.type, 
      cast( a.database_backup_lsn as varchar(25)) as database_backup_lsn,
      cast( a.checkpoint_lsn as varchar(25)) as checkpoint_lsn
FROM msdb.dbo.backupset a INNER JOIN
      msdb.dbo.backupmediafamily c ON a.media_set_id = c.media_set_id
WHERE (a.database_creation_date =
          (SELECT CONVERT(varchar(20), crdate, 120)
         FROM master.dbo.sysdatabases
         WHERE dbid = db_id()))
ORDER BY a.backup_start_date desc
go

/*==============================================================*/
/* View: V_C_ErrRec                                             */
/*==============================================================*/
create view dbo.V_C_ErrRec as
SELECT 
      dbo.T_C_ErrRec.fKeyID AS 序号, 
      dbo.T_B_Employee.fName AS 姓名, 
      dbo.T_C_ErrRec.fAccount_id AS 账号, 
      dbo.T_C_ErrRec.fCard_Number AS 卡号, 
      dbo.T_B_Dept.fDeptName AS 部门, 
      dbo.T_C_ErrRec.fPos_id AS 机号, 
      dbo.T_B_Pos.fPosName AS 机器名, 
      dbo.T_B_MealSet.fMeal_Name AS 消费班次, 
      dbo.T_C_ConsState.fStateName AS 消费类型, 
      dbo.T_C_ErrRec.fCons_Time AS 发生时间, 
      dbo.T_C_ErrRec.fGatherTime AS 收取时间, 
      dbo.T_C_ErrRec.fOdd_Money AS 原余额, 
      dbo.T_C_ErrRec.fCons_Fare AS 交易额, 
      dbo.T_C_ErrRec.fX_Money AS 现余额, 
      dbo.T_C_ErrRec.fSx_Money AS 手续费, 
      dbo.T_B_Employee.fEmployeeCode AS 工号, 
      dbo.T_B_Station.fStation_Name AS 工作站, 
      dbo.T_B_Manager.fOperName AS 操作员,
      dbo.T_C_ErrRec.fOper_ID AS 操作员编号,
      dbo.T_C_ErrRec.fCons_State AS 消费类型编码,
      dbo.T_C_ErrRec.fFktime AS 写卡次数,
      dbo.T_C_ErrRec.fdp_bh AS 部门代码,
      dbo.T_C_ErrRec.fstation_id AS 工作站编号,
      dbo.T_C_ErrRec.fCpID AS 菜品编号,
      dbo.T_C_ErrRec.fCpCount AS 菜品份数
FROM dbo.T_C_ErrRec LEFT OUTER JOIN 
	dbo.T_B_Pos ON dbo.T_B_Pos.fPosID = dbo.T_C_ErrRec.fPos_id  INNER JOIN 
	dbo.T_B_Station  ON dbo.T_B_Station.fStation_Id = SUBSTRING(dbo.T_B_Pos.fSiteID, 1, 2) LEFT OUTER JOIN   
      dbo.T_B_Employee ON 
      dbo.T_C_ErrRec.fAccount_id = dbo.T_B_Employee.fAccountID LEFT OUTER JOIN
      dbo.T_B_Dept ON 
      dbo.T_C_ErrRec.fDp_bh = dbo.T_B_Dept.fDeptCode LEFT OUTER JOIN
      dbo.T_B_Manager ON 
      dbo.T_C_ErrRec.fOper_id = dbo.T_B_Manager.fOperID LEFT OUTER JOIN
      dbo.T_B_MealSet ON 
      dbo.T_C_ErrRec.fMeal_id = dbo.T_B_MealSet.fMeal_Id LEFT OUTER JOIN
      dbo.T_C_ConsState ON 
      dbo.T_C_ErrRec.fCons_State = dbo.T_C_ConsState.fStateID
go

/*==============================================================*/
/* View: V_C_SUM_OPER                                           */
/*==============================================================*/
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: V_C_SUM_Pos                                            */
/*==============================================================*/
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

/*==============================================================*/
/* View: V_C_Subsidizes                                         */
/*==============================================================*/
create view dbo.V_C_Subsidizes as
SELECT R.fKeyID, R.fAccountID, R.fSubMoney, R.fSubTime, R.fReceiveTime, R.fOperID, 
      R.fReceived, E.fSerialNo, E.fName, E.fDept, D.fDeptName, E.fCard_State, 
      R.fStartReceiveDate, R.fEndReceiveDate, R.fYear,R.fMonth,R.fClearSub,R.fSubID,
      R.fLastMoney, R.fRequested, R.fPurseCode
FROM T_C_Subsidizes R INNER JOIN
     T_B_Employee E ON  R.fAccountID = E.fAccountID INNER JOIN
     T_B_Dept D ON E.fDept = D.fDeptCode
go

/*==============================================================*/
/* View: V_Cons_Record                                          */
/*==============================================================*/
create view dbo.V_Cons_Record as
SELECT 
	''[fKeyID],
	'' [fAccountID],
	GETDATE() [fDate],
	0  [fPurseID],
	0 [fOldBalance],
	0 [fConsCount],
	0 [fConsMoney],
	0 [fSaveCount],
	0 [fSaveMoney],
	0 [fTakeCount],
	0 [fTakeMoney],
	0 [fSubCount],
	0 [fSubMoney],
	0 [fClearCount],
	0 [fClearMoney],
	0 [fPutRightCount] ,
	0 [fPutRightMoney],
	0 [fDiscountCount],
	0 [fDiscountMoney],
	0 [fFee1],
	0 [fFee2],
	0 [fFee3],
	0 [fFee4],
	0 [fNewBalance]
go

/*==============================================================*/
/* View: V_Cons_RecordTMP                                       */
/*==============================================================*/
create view dbo.V_Cons_RecordTMP as
SELECT 
	''[fKeyID],
	'' [fAccountID],
	GETDATE() [fDate],
	0  [fPurseID],
	0 [fOldBalance],
	0 [fConsCount],
	0 [fConsMoney],
	0 [fSaveCount],
	0 [fSaveMoney],
	0 [fTakeCount],
	0 [fTakeMoney],
	0 [fSubCount],
	0 [fSubMoney],
	0 [fClearCount],
	0 [fClearMoney],
	0 [fPutRightCount] ,
	0 [fPutRightMoney],
	0 [fDiscountCount],
	0 [fDiscountMoney],
	0 [fFee1],
	0 [fFee2],
	0 [fFee3],
	0 [fFee4],
	0 [fNewBalance]
go

/*==============================================================*/
/* View: V_E_EmpRule                                            */
/*==============================================================*/
create view dbo.V_E_EmpRule as
SELECT  T_E_EmpRule.fKeyID, T_E_EmpRule.fAccountID,   
      T_E_EmpRule.fEnable, T_E_EmpRule.fPosID, T_E_EmpRule.fCtrlRuleID,   
      T_B_Employee.[fName], T_B_Cards.fSerialNo, T_B_Employee.fEgsPass,   
      T_B_Employee.fXgEnable, T_E_EmpRule.fDeadLine,  
      CASE T_E_EmpRule.fCtrlRuleID WHEN 255 THEN '自定义规则' ELSE T_E_PassRule.fCtrlRuleName END AS fCtrlRuleName,  
      CASE T_E_EmpRule.fCtrlRuleID WHEN 255 THEN T_E_EmpRule.fDoor1Rule ELSE T_E_CtrlRule.fDoor1Rule END AS fDoor1Rule,  
      CASE T_E_EmpRule.fCtrlRuleID WHEN 255 THEN T_E_EmpRule.fDoor2Rule ELSE T_E_CtrlRule.fDoor2Rule END AS fDoor2Rule,  
      CASE T_E_EmpRule.fCtrlRuleID WHEN 255 THEN T_E_EmpRule.fDoor3Rule ELSE T_E_CtrlRule.fDoor3Rule END AS fDoor3Rule,  
      CASE T_E_EmpRule.fCtrlRuleID WHEN 255 THEN T_E_EmpRule.fDoor4Rule ELSE T_E_CtrlRule.fDoor4Rule END AS fDoor4Rule  
FROM T_E_EmpRule LEFT OUTER JOIN  
      T_E_PassRule ON   
      T_E_EmpRule.fCtrlRuleID = T_E_PassRule.fCtrlRuleID LEFT OUTER JOIN  
      T_B_Employee ON   
      T_E_EmpRule.fAccountID = T_B_Employee.fAccountID LEFT OUTER JOIN  
      T_E_CtrlRule ON T_E_EmpRule.fPosID = T_E_CtrlRule.fPosID AND   
      T_E_EmpRule.fCtrlRuleID = T_E_CtrlRule.fCtrlRuleID LEFT OUTER JOIN 
      T_B_Cards ON T_E_EmpRule.fAccountID=T_B_Cards.fAccountID and T_B_Cards.fCardState<>4 INNER JOIN 
      T_B_CardType ON T_B_Cards.fCardTypeID=T_B_CardType.fCardTypeID AND T_B_CardType.fIsMainCard=1
go

/*==============================================================*/
/* View: V_E_ErrorRec                                           */
/*==============================================================*/
create view dbo.V_E_ErrorRec as
SELECT dbo.T_E_ErrorRec.fPosID AS 控制器机号, 
      dbo.T_B_Pos.fPosName AS 控制器名称, dbo.T_E_ErrorRec.fErrorCode AS 错误代码, 
      dbo.T_E_ErrorRec.fErrorTime AS 发生时间, 
      dbo.T_E_ErrorRec.fErrorExplain AS 错误描述
FROM dbo.T_E_ErrorRec INNER JOIN
      dbo.T_B_Pos ON dbo.T_E_ErrorRec.fPosID = dbo.T_B_Pos.fPosID
go

alter table dbo.T_E_CardReader
   add constraint FK_T_E_CardReader_T_B_Pos foreign key (fPosID)
      references dbo.T_B_Pos (fPosID)
         on update cascade on delete cascade 
         not for replication
go

alter table dbo.T_E_CtrlRule
   add constraint FK_T_E_CtrlRule_T_B_Pos foreign key (fPosID)
      references dbo.T_B_Pos (fPosID)
         on update cascade on delete cascade 
         not for replication
go

alter table dbo.T_E_Door
   add constraint FK_T_E_Door_T_B_Pos foreign key (fPosID)
      references dbo.T_B_Pos (fPosID)
         on update cascade on delete cascade 
         not for replication
go

alter table dbo.T_E_DoorRule
   add constraint FK_T_E_DoorRule_T_B_Pos foreign key (fPosId)
      references dbo.T_B_Pos (fPosID)
         on update cascade on delete cascade 
         not for replication
go

alter table dbo.T_E_EmpRule
   add constraint FK_T_E_EmpRule_T_B_Employee foreign key (fAccountID)
      references dbo.T_B_Employee (fAccountID)
         on update cascade on delete cascade 
         not for replication
go

alter table dbo.T_E_EmpRule
   add constraint FK_T_E_EmpRule_T_B_Pos foreign key (fPosID)
      references dbo.T_B_Pos (fPosID)
         on update cascade on delete cascade 
         not for replication
go


create function dbo.FN_CastAtdRecType (@RecType int)
RETURNS varchar(30) 
AS  
BEGIN 
declare @ReStr varchar(30)
	Set @ReStr=
	CASE @RecType 
	WHEN 1 THEN '正常打卡'
	WHEN 2 THEN '非正常打卡'
	WHEN 3 THEN '不在打卡时间'
	WHEN 9 THEN '人工打卡'
	WHEN 51 THEN '挂失卡'
	WHEN 68 THEN '锁定卡'
	END
RETURN @ReStr
END
go


create function dbo.FN_CastEgsRecType (@RecType int)
RETURNS varchar(30) 
AS  
BEGIN 
declare @ReStr varchar(30)
	Set @ReStr=
	CASE @RecType 
	    WHEN 1 THEN '开锁' 
 	    WHEN 2 THEN '关锁' 
	    WHEN 3 THEN '报警' 
	    WHEN 4 THEN '考勤打卡' 
	    WHEN 5 THEN '巡更' 
	    WHEN 6 THEN '关门超时' 
	    WHEN 7 THEN '开门超时' 
	    WHEN 8 THEN '胁迫开门' 
	    WHEN 9 THEN '胁迫关门' 
	    WHEN 10 THEN '非法开门' 
	    WHEN 11 THEN '关报警' 
	    WHEN 12 THEN '按钮开门' 
	    WHEN 13 THEN '超级密码开门' 
	    WHEN 14 THEN '普通密码开门' 
	    WHEN 15 THEN '无效刷卡(卡到期或规则不允许)' 
	    WHEN 16 THEN '非法打卡' 
	    WHEN 17 THEN '门打开' 
	    WHEN 18 THEN '门关闭' 
	    WHEN 19 THEN '非法卡报警' 
	    WHEN 20 THEN '无效时间刷卡' 
	    WHEN 21 THEN '门互锁开门失败' 
	    WHEN 22 THEN '防尾随开门失败' 
	    WHEN 23 THEN '工作电压低'
	ELSE ''	
	END
RETURN @ReStr
END
go


create function dbo.FN_FillZero (@FillLen int,@GetNum int)
RETURNS varchar(20) 
AS  
BEGIN 
declare @ReChar varchar(20)
SET @ReChar=cast(@GetNum as varchar)
	WHILE Len(@ReChar) < @FillLen
	BEGIN
		SET @ReChar='0'+@ReChar
	END
	RETURN @ReChar
END
go


create function dbo.FN_GetCalcBinary (@iNo tinyint,
 @State tinyint=1)
RETURNS int 
AS  
BEGIN 	
DECLARE @Result int
IF @State=1
BEGIN
	SET @Result= CASE 
	WHEN @iNo=0 THEN 1
	WHEN @iNo=1 THEN 128
	WHEN @iNo=2 THEN 64
	WHEN @iNo=3 THEN 32
	WHEN @iNo=4 THEN 16
	WHEN @iNo=5 THEN 8
	WHEN @iNo=6 THEN 4
	WHEN @iNo=7 THEN 2
	END
END
ELSE BEGIN
	SET @Result= CASE 
	WHEN @iNo=0 THEN 254
	WHEN @iNo=1 THEN 127
	WHEN @iNo=2 THEN 191
	WHEN @iNo=3 THEN 223
	WHEN @iNo=4 THEN 239
	WHEN @iNo=5 THEN 247
	WHEN @iNo=6 THEN 251
	WHEN @iNo=7 THEN 253
	END	
END
RETURN @Result
END
go


create function dbo.FN_GetOughtDays (@AccountID varchar(18),
	@BeginDate datetime,
	@EndTime datetime)
RETURNS int 
AS  
BEGIN 
declare @Result int
declare @i int
declare @Count int
declare @now datetime
declare @sqlwhere varchar(100)

set @Count=0
set @now=@BeginDate
--while (year(@now)<=year(@EndTime)) and (month(@now)=month(@EndTime))
while DATEDIFF(mm,@now,@EndTime)>=0
begin
set @i=0
SELECT 	@i= CASE WHEN (fDay1 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-1' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-1'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay2 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-2' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-2'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay3 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-3' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-3'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay4 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-4' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-4'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay5 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-5' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-5'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay6 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-6' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-6'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay7 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-7' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-7'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay8 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-8' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-8'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay9 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-9' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-9'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay10 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-10' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-10'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay11 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-11' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-11'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay12 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-12' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-12'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay13 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-13' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-13'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay14 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-14' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-14'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay15 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-15' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-15'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay16 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-16' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-16'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay17 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-17' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-17'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay18 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-18' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-18'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay19 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-19' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-19'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay20 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-20' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-20'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay21 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-21' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-21'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay22 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-22' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-22'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay23 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-23' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-23'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay24 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-24' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-24'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay25 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-25' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-25'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay26 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-26' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-26'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay27 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-27' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-27'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN (fDay28 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-28' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-28'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN DateName(mm,@now)<>2 and (fDay29 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-29' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-29'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN DateName(mm,@now)<>2 and (fDay30 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-30' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-30'<=@EndTime) THEN 1 ELSE 0 END +
	CASE WHEN DateName(mm,@now) in (1,3,5,7,8,10,12) and (fDay31 <>'') and (DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-31' >=@BeginDate and DateName(yyyy,@now)+'-'+DateName(mm,@now)+'-31'<=@EndTime) THEN 1 ELSE 0 END 
FROM T_A_WTArrange WHERE fAccountID=@AccountID and fYear=Year(@Now) and fMonth=Month(@Now)

if (@i is null) or (@i='') set @i=0

set @Count=@Count+@i
Set @Now=DateAdd(mm,1,@Now)
end

Return @Count

END
go

create procedure dbo.RS_Day 
    @DeptCode varchar(20),
  	@timeBegin varchar(20),
  	@timeEnd varchar(20) 
  	as
DECLARE @strsql nvarchar(4000)

SET @strsql='SELECT dbo.T_A_ReportDays.fAccountID AS 账号, 
      dbo.T_B_Employee.fName AS 姓名,
      dbo.T_B_Employee.fCardNo AS 卡号,
      dbo.T_B_Employee.fEmployeeCode AS 工号,
      dbo.T_A_WorkTime.fWorkTimeName AS 班次,
      dbo.T_A_ReportDays.fCheckDate AS 考勤日期, 
      dbo.T_A_ReportDays.fWeekday AS 星期, 
      dbo.T_A_ReportDays.fOnDuty1 AS 签到时间一, 
      dbo.T_A_ReportDays.fOffDuty1 AS 签退时间一, 
      dbo.T_A_ReportDays.fOnDuty2 AS 签到时间二, 
      dbo.T_A_ReportDays.fOffDuty2 AS 签退时间二, 
      dbo.T_A_ReportDays.fOnDuty3 AS 签到时间三, 
      dbo.T_A_ReportDays.fOffDuty3 AS 签退时间三, 
      dbo.T_A_ReportDays.fOnDuty4 AS 签到时间四, 
      dbo.T_A_ReportDays.fOffDuty4 AS 签退时间四, 
      dbo.T_A_ReportDays.fOnDuty5 AS 签到时间五, 
      dbo.T_A_ReportDays.fOffDuty5 AS 签退时间五, 
      dbo.T_A_ReportDays.fOnDuty6 AS 签到时间六, 
      dbo.T_A_ReportDays.fOffDuty6 AS 签退时间六, 
      dbo.T_A_ReportDays.fManHour AS 工时, 
      dbo.T_A_ReportDays.fOverdueCount AS 迟到次数, 
      dbo.T_A_ReportDays.fOverdueMinutes AS 迟到分钟, 
      dbo.T_A_ReportDays.fEarlyCount AS 早退次数, 
      dbo.T_A_ReportDays.fEarlyMinutes AS 早退分钟, 
      dbo.T_A_ReportDays.fAbsentDays AS 旷工天数, 
      dbo.T_A_ReportDays.fAbsentMinutes AS 旷工分钟, 
      dbo.T_A_ReportDays.fLeaveDays AS 请假天数, 
      dbo.T_A_ReportDays.fLeaveMinutes AS 请假分钟, 
      dbo.T_A_ReportDays.fEvectionDays AS 出差天数, 
      dbo.T_A_ReportDays.fEvectionMinutes AS 出差分钟, 
      dbo.T_A_ReportDays.fOvertimeMinutes AS 加班分钟, 
      dbo.T_A_ReportDays.fExplain AS 说明             
FROM dbo.T_A_ReportDays 
INNER JOIN  dbo.T_B_Employee ON 
      dbo.T_A_ReportDays.fAccountID = dbo.T_B_Employee.fAccountID and dbo.T_B_Employee.fDept like '''+@DeptCode+'%''  
LEFT OUTER JOIN  dbo.T_A_WorkTime ON 
      dbo.T_A_ReportDays.fWorkTimeCode = dbo.T_A_WorkTime.fWorkTimeCode 
WHERE dbo.T_A_ReportDays.fCheckDate>='''+@timeBegin+''' and dbo.T_A_ReportDays.fCheckDate<='''+@timeEnd+''''
exec sp_executesql @strsql
--print @strsql
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]   [money] 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


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


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] [money]  NOT NULL,
		[fDayCount] [int] NOT NULL DEFAULT ((0)),
		[fMeal1Money] [money]  NOT NULL DEFAULT ((0.00)),
		[fMeal1Count] [int] NOT NULL DEFAULT ((0)),
		[fMeal2Money] [money]  NOT NULL DEFAULT ((0.00)),
		[fMeal2Count] [int] NOT NULL DEFAULT ((0)),
		[fMeal3Money] [money]  NOT NULL DEFAULT ((0.00)),
		[fMeal3Count] [int] NOT NULL DEFAULT ((0)),
		[fMeal4Money] [money]  NOT NULL DEFAULT ((0.00)),
		[fMeal4Count] [int] NOT NULL DEFAULT ((0)),
		[fMeal5Money] [money]  NOT NULL DEFAULT ((0.00)),
		[fMeal5Count] [int] NOT NULL DEFAULT ((0)),
		[fMeal6Money] [money]  NOT NULL DEFAULT ((0.00)),
		[fMeal6Count] [int] NOT NULL DEFAULT ((0)),
		[fMeal7Money] [money]  NOT NULL DEFAULT ((0.00)),
		[fMeal7Count] [int] NOT NULL DEFAULT ((0)),
		[fMeal8Money] [money]  NOT NULL DEFAULT ((0.00)),
		[fMeal8Count] [int] NOT NULL DEFAULT ((0)),
		[fLimitMeal1Money] [money]  NOT NULL DEFAULT ((0.00)),
		[fLimitMeal1Count] [int] NOT NULL DEFAULT ((0)),
		[fLimitMeal2Money] [money]  NOT NULL DEFAULT ((0.00)),
		[fLimitMeal2Count] [int] NOT NULL DEFAULT ((0)),
		[fLimitMeal3Money] [money]  NOT NULL DEFAULT ((0.00)),
		[fLimitMeal3Count] [int] NOT NULL DEFAULT ((0)),
		[fLimitMeal4Money] [money]  NOT NULL DEFAULT ((0.00)),
		[fLimitMeal4Count] [int] NOT NULL DEFAULT ((0)),
		[fLimitMeal5Money] [money]  NOT NULL DEFAULT ((0.00)),
		[fLimitMeal5Count] [int] NOT NULL DEFAULT ((0)),
		[fLimitMeal6Money] [money]  NOT NULL DEFAULT ((0.00)),
		[fLimitMeal6Count] [int] NOT NULL DEFAULT ((0)),
		[fLimitMeal7Money] [money]  NOT NULL DEFAULT ((0.00)),
		[fLimitMeal7Count] [int] NOT NULL DEFAULT ((0)),
		[fLimitMeal8Money] [money]  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


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] [money]  NOT NULL,  
  [fConsCount] [int] NOT NULL DEFAULT ((0)),  
  [fConsMoney] [money]  NOT NULL DEFAULT ((0.00)),
  [fLimitConsCount] [int] NOT NULL DEFAULT ((0)),  
  [fLimitConsMoney] [money]  NOT NULL DEFAULT ((0.00)),    
  [fSaveCount] [int] NOT NULL DEFAULT ((0)),  
  [fSaveMoney] [money]  NOT NULL DEFAULT ((0.00)),  
  [fTakeCount] [int] NOT NULL DEFAULT ((0)),  
  [fTakeMoney] [money]  NOT NULL DEFAULT ((0.00)),  
  [fSubCount] [int] NOT NULL DEFAULT ((0)),  
  [fSubMoney] [money]  NOT NULL DEFAULT ((0.00)),  
  [fClearCount] [int] NOT NULL DEFAULT ((0)),  
  [fClearMoney] [money]  NOT NULL DEFAULT ((0.00)),  
  [fPutRightCount] [int] NOT NULL DEFAULT ((0)),  
  [fPutRightMoney] [money]  NOT NULL DEFAULT ((0.00)),  
  [fDiscountCount] [int] NOT NULL DEFAULT ((0)),  
  [fDiscountMoney] [money]  NOT NULL DEFAULT ((0.00)),  
  [fFee1] [money]  NOT NULL DEFAULT ((0.00)),  
  [fFee2] [money]  NOT NULL DEFAULT ((0.00)),  
  [fFee3] [money]  NOT NULL DEFAULT ((0.00)),  
  [fFee4] [money]  NOT NULL DEFAULT ((0.00)),  
  [fNewBalance] [money]  NOT NULL,   
        ' + @PRI  + '  
  ) ON [PRIMARY]   
  ' + @EndSQL  
  print @createsql  
  exec(@createsql)  
  if @@error <> 0   
  begin  
    Set @Ret = ''  
    Return  
  end  
 end
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


create procedure dbo.SP_GetEmpSumInfoByCash 
     @datetime datetime,  
     @StationID varchar(2),  
     @PurseID int 
     as
DECLARE @sDate    VARCHAR(20)   --查询日期  
 DECLARE @sDateBegin    VARCHAR(20)   --查询日期  
 DECLARE @sDateEnd    VARCHAR(20)   --查询日期  
 DECLARE @TabSQL nVARCHAR(4000)   
 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 @StationID=''   
  SET @StrAct = ''
 ELSE  
  SET @StrAct =' AND fAccountID in (select  fAccountID from T_C_Cashdata'+@StationID+' )'
 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   
  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  
   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  
   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    
   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
go


create procedure dbo.SP_GetEmpSumInfo_Backstage 
     @datetime datetime,      
     @AccountID varchar(8),      
     @PurseID int 
     as
begin 
  --返回结果临时表   
  create table #Result
  (
				faccountid varchar(10),
				fpurseID int,
				famount1 money  not null default 0.00,
				fcount1 int not null default 0,
				famountlimit1 money not null default 0.00,
				fcountlimit1 int not null default 0,
				famount2 money not null default 0.00,
				fcount2 int not null default 0,
				famountlimit2 money not null default 0.00,
				fcountlimit2 int not null default 0,
				famount3 money not null default 0.00,
				fcount3 int  not null default 0,
				famountlimit3 money not null default 0.00,
				fcountlimit3 int not null default 0,
				famount4 money not null default 0.00,
				fcount4 int  not null default 0,
				famountlimit4 money not null default 0.00,
				fcountlimit4 int not null default 0,
				famount5 money not null default 0.00,
				fcount5 int  not null default 0,
				famountlimit5 money not null default 0.00,
				fcountlimit5 int not null default 0,
				famount6 money not null default 0.00,
				fcount6 int  not null default 0,
				famountlimit6 money not null default 0.00,
				fcountlimit6 int not null default 0,
				famount7 money not null default 0.00,
				fcount7 int  not null default 0,
				famountlimit7 money not null default 0.00,
				fcountlimit7 int not null default 0,
				famount8 money not null default 0.00,
				fcount8 int  not null default 0,
				famountlimit8 money not null default 0.00,
				fcountlimit8 int not null default 0,
				famount_d money not null default 0.00,
				fcount_d int  not null default 0,
				famountlimit_d money not null default 0.00,
				fcountlimit_d int not null default 0,
				famount_w money not null default 0.00,
				fcount_w  int  not null default 0,
				famountlimit_w  money not null default 0.00,
				fcountlimit_w  int not null default 0,
				famount_m  money not null default 0.00,
				fcount_m  int  not null default 0,
				famountlimit_m  money not null default 0.00,
				fcountlimit_m  int not null default 0,
				famount_y  money not null default 0.00,
				fcount_y int  not null default 0,
				famountlimit_y money not null default 0.00,
				fcountlimit_y int not null default 0,
				fputrightamount_d money 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


create procedure dbo.SP_GetEmpSumInfo_Interface 
     @datetime datetime,      
     @AccountID varchar(8),      
     @PurseID int 
     as
begin 
  --返回结果临时表   
  create table #Result
  (
				faccountid varchar(10),
				fpurseID int,
				famount1 money  not null default 0.00,
				fcount1 int not null default 0,
				famountlimit1 money not null default 0.00,
				fcountlimit1 int not null default 0,
				famount2 money not null default 0.00,
				fcount2 int not null default 0,
				famountlimit2 money not null default 0.00,
				fcountlimit2 int not null default 0,
				famount3 money not null default 0.00,
				fcount3 int  not null default 0,
				famountlimit3 money not null default 0.00,
				fcountlimit3 int not null default 0,
				famount4 money not null default 0.00,
				fcount4 int  not null default 0,
				famountlimit4 money not null default 0.00,
				fcountlimit4 int not null default 0,
				famount5 money not null default 0.00,
				fcount5 int  not null default 0,
				famountlimit5 money not null default 0.00,
				fcountlimit5 int not null default 0,
				famount6 money not null default 0.00,
				fcount6 int  not null default 0,
				famountlimit6 money not null default 0.00,
				fcountlimit6 int not null default 0,
				famount7 money not null default 0.00,
				fcount7 int  not null default 0,
				famountlimit7 money not null default 0.00,
				fcountlimit7 int not null default 0,
				famount8 money not null default 0.00,
				fcount8 int  not null default 0,
				famountlimit8 money not null default 0.00,
				fcountlimit8 int not null default 0,
				
				fConsCountD int not null default 0,
				fConsMoneyD money  not null default 0.00,
				fSaveCountD int not null default 0,
				fSaveMoneyD money  not null default 0.00,
				fTakeCountD int not null default 0,
				fTakeMoneyD money  not null default 0.00,
				fSubCountD int not null default 0,
				fSubMoneyD money  not null default 0.00,
				fClearCountD int not null default 0,
				fClearMoneyD money  not null default 0.00,
				fPutRightCountD int not null default 0,
				fPutRightMoneyD money  not null default 0.00,
				fConsCountM int not null default 0,
				fConsMoneyM money  not null default 0.00,
				fSaveCountM int not null default 0,
				fSaveMoneyM money  not null default 0.00,
				fTakeCountM int not null default 0,
				fTakeMoneyM money  not null default 0.00,
				fSubCountM int not null default 0,
				fSubMoneyM money  not null default 0.00,
				fClearCountM int not null default 0,
				fClearMoneyM money  not null default 0.00,
				fPutRightCountM int not null default 0,
				fPutRightMoneyM money  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


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


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] [money]  NOT NULL,      
  [fAmount] [money]  NOT NULL,      
  [fNewBalance] [money]  NOT NULL,      
  [fFee1] [money]  NULL,      
  [fFee2] [money]  NULL,                     
  [fFee3] [money]  NULL,      
  [fFee4] [money]  NULL,       
  [fDiscount] [money]  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] [money]  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


create procedure dbo.SP_Wst_GetRecMax 
   @MaxID int output 
   as
begin	
  update T_B_SysParam Set fParamValue = fParamValue + 1 where fParamName = 'RecCount'
  Select @MaxID = ISNULL(cast(fParamValue as bigint),0) from T_B_SysParam where fParamName = 'RecCount'
end
go


create procedure dbo.SP_Wst_InsOtherStation 
    @accountid varchar(18), 
  	@SerialNo [varchar](30), 
  	@NewSerialNo [varchar](30), 
  	@AppID int,
  	@ConsTime datetime, 
  	@Cons_State varchar(2),
  	@TransMoney  money , 
  	@Station_id varchar(2) 
  	as
Begin
  declare @StationID varchar(2)
  declare @RecTable varchar(40)
  declare @ExSQL varchar(1000)
  declare  curStation cursor for
  SELECT fStation_Id  FROM T_B_Station
  open curStation  
  fetch next  from curStation into @StationID
  while @@fetch_status=0  
  begin
    if @StationID <> @Station_id  --当查询出的工作站信息不是当前工作站的时候才写入对应的工作站
    begin
      Set @RecTable = 'T_C_Cashdata' + @StationID
      Set @ExSQL = 
      ' INSERT INTO ' + @RecTable + '
           (fAccount_id ,fCard_Number,fNewCard_Number ,fAppID ,fCons_Time,
            fCons_State ,fCons_Fare  ,fStation_id )
       VALUES (
      ''' + @accountid + ''',''' + @SerialNo + ''',''' + @NewSerialNo+ ''','+ CAST(@AppID as varchar(2)) + ',''' + CONVERT(varchar(100), @ConsTime, 20) + ''',
      ''' + @Cons_State + ''',' + cast(@TransMoney as varchar(20)) + ',''' + @Station_id + ''' )'
      Print @ExSQL
      Exec(@ExSQL)
    end
	fetch next from curStation into  @StationID 
  end
  close curStation
  deallocate  curStation
end
go


create procedure dbo.SP_Wst_UPStation 
as
begin
  declare @StationID varchar(2)
  declare @RecTable varchar(40)
  declare @ExSQL varchar(1000)
  declare  curStation cursor for
  SELECT fStation_Id  FROM T_B_Station
  open curStation  
  fetch next  from curStation into @StationID
  while @@fetch_status=0  
  begin
    Set @RecTable = 'T_C_Cashdata' + @StationID
    set @ExSQL =
    'if not EXISTS(select id from syscolumns where name=''fNewCard_Number'' and [id]=object_id('''+ @RecTable +''')) '+
      ' alter table '+ @RecTable +' add fNewCard_Number varchar(30)  '
    print @ExSQL
    Exec(@ExSQL)
	fetch next from curStation into  @StationID 
  end
  close curStation
  deallocate  curStation
end
go


create procedure dbo.UP_AutoBackupDatabase 
as
declare @BackupTime datetime
set @BackupTime=getdate()
declare @LastBackupDate datetime	--最后一次备份时间
declare @BackupDatabasePath varchar(200)
declare @LastBackupStyle int		--最后一次备份方式 0:自动备份 1:手工备份
select @LastBackupDate=fParamValue,@LastBackupStyle=fRestrict from T_B_SysParam where fParamName='LastFullBackupDate'
select @BackupDatabasePath=fParamValue  from T_B_SysParam where fParamName='BackupDatabasePath'

--判断备份路径是否存在
if @BackupDatabasePath<>'' 
BEGIN
	declare @DirExists bit
	CREATE TABLE #tmp ([FileExists] BIT, [DirExists] BIT, [ParentDirExists] BIT)
	INSERT INTO #tmp ([FileExists], [DirExists], [ParentDirExists]) 
	EXEC master.dbo.xp_fileexist @BackupDatabasePath
	select @DirExists=DirExists from #tmp
	if @DirExists=0 begin
	select -1 as ResultID, '自动备份路径设置不正确，请检查系统参数设置' as ResultMsg
	RETURN
	end
END

--得到当前数据库名
declare @DBName varchar(100)
/*
CREATE TABLE #TempTable (
	spid int,
	exid int,
	status varchar(50),
	loginame varchar(200),
	hostname varchar(200),
	blk int,
	dbname varchar(200),
    	cmd varchar(200)
)
insert #TempTable Exec sp_who @@spid
select @DBName=dbname from #TempTable
*/
set @DBName=db_name()


declare @BackupFile varchar(500)
declare @BackupDays int	--完全备份周期，现定于7日
set @BackupDays=7
--如果距离最后一次完全备份超过7天，或最后一次备份为手工备份，则进行完全备份，否则进行差异备份
if (@LastBackupDate='') or (@LastBackupDate is null) or (DATEDIFF(dd,@LastBackupDate,@BackupTime)>@BackupDays) or (@LastBackupStyle=1)
begin
	set @BackupFile=@BackupDatabasePath+@DBName+'_BackupData_Full_'+convert(varchar(30),@BackupTime,112)+'.bak'
	backup database @DBName to disk=@BackupFile with init
	update T_B_SysParam Set fParamValue=@BackupTime, fRestrict=0 where fParamName='LastFullBackupDate' 	
end
else begin
	set @BackupFile=@BackupDatabasePath+@DBName+'_BackupData_Differ_'+convert(varchar(30),@BackupTime,112)+'.bak' 
	backup database @DBName to disk=@BackupFile with init, DIFFERENTIAL
end

select 0 as ResultID, '备份成功' as ResultMsg

--select  @LastBackupDate,@BackupDatabasePath,@BackupFile
go


create procedure dbo.UP_BuildReportMonth 
    @AccountID varchar(18),
  	@Year int,
  	@Month int 
  	as
BEGIN
	--set @AccountID='00000005'
	--set @Year=2007
	--set @Month=11

	declare @begindate datetime
	declare @enddate datetime
	declare @monthadd int
	select @monthadd=fParamValue from T_B_SysParam where fParamName='MonthBegin'

	set @begindate= cast(@Year as varchar(4))+'-'+cast(@Month as varchar(2))+'-1'

	if @monthadd>=0 
	begin
		set @begindate= @begindate+ @monthadd	
	end 
	else begin
		set @begindate=dateadd(mm,-1,@begindate)+abs(@monthadd)-1
	end

    set @Enddate= DateAdd(mm,1,@begindate)-1
	------set @Enddate=DateAdd(HH,23,@Enddate) ------取当天的晚上11点

	Delete From T_A_ReportMonths Where fAccountID=@AccountID and fYear=@Year and fMonth=@Month

	--select @monthadd,@begindate,@Enddate,dbo.FN_GetOughtDays(@AccountID,@BeginDate,@Enddate)

    set @begindate=dateadd(day,-1,@begindate)
    set @Enddate=dateadd(day,-1,@Enddate+'23:59:59')
    
	Insert into T_A_ReportMonths
	select 	fAccountID,@year,@Month,dbo.FN_GetOughtDays(@AccountID,@BeginDate,@Enddate),Sum(fDays),Sum(fOverdueCount),Sum(fOverdueMinutes),  
		Sum(fEarlyCount),Sum(fEarlyMinutes),Sum(fAbsentDays),Sum(fAbsentMinutes),Sum(fLeaveDays),Sum(fLeaveMinutes),
		Sum(fEvectionDays),Sum(fEvectionMinutes),Sum(fOvertimeMinutes),Sum(fManHour)
	from T_A_ReportDays where fAccountID=@AccountID and (fCheckDate>=@begindate and fCheckDate<=@Enddate)
	group by fAccountID
END
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


create procedure dbo.UP_CheckRecTable 
    @year int,
  	@month int 
  	as
declare @TableName varchar(30)
declare @createsql nvarchar(1000)
set @TableName='T_A_CardRecord_'+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 ,'+
		'[fRecordedType] [tinyint] NOT NULL DEFAULT (0),'+
		'[fAccountID] [varchar] (18) COLLATE Chinese_PRC_CI_AS NOT NULL ,'+
		'[fCardNo] [varchar] (12) COLLATE Chinese_PRC_CI_AS NOT NULL ,'+
		'[fRecordedTime] [datetime] NOT NULL ,'+
		'[fReceiveTime] [datetime] NOT NULL DEFAULT (getdate()),'+
		'[fPosID] [int] NOT NULL ,'+
		'[fOperID] [int] NOT NULL ,'+
		'CONSTRAINT [PK_'+@TableName+'] PRIMARY KEY  CLUSTERED '+
		'('+
		'	[fKeyID]'+
		')  ON [PRIMARY]'+ 
	') ON [PRIMARY]'
--	print @createsql
	exec sp_executesql @createsql

	set @createsql= 'CREATE 
	  INDEX [FK_'+@TableName+'] ON [dbo].['+@TableName+'] ([fAccountID], [fRecordedTime])'
	exec sp_executesql @createsql
end

set @TableName='T_A_CardRecordPic_'+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] NOT NULL ,'+
		'[fAccountID] [varchar] (18) COLLATE Chinese_PRC_CI_AS NOT NULL ,'+
		'[fRecordedTime] [datetime] NOT NULL ,'+
		'[fRecPic] [image] NULL ,'+
		'CONSTRAINT [PK_'+@TableName+'] PRIMARY KEY  CLUSTERED '+
		'('+
		'	[fKeyID]'+
		')  ON [PRIMARY]'+ 
	') ON [PRIMARY]'
	exec sp_executesql @createsql
end
go


create procedure dbo.UP_DirExists 
  @DirName varchar(200) 
  as
CREATE TABLE #tmp ([FileExists] BIT, [DirExists] BIT, [ParentDirExists] BIT)
INSERT INTO #tmp ([FileExists], [DirExists], [ParentDirExists]) 
EXEC master.dbo.xp_fileexist @DirName
SELECT * FROM #tmp
DROP TABLE #tmp
go


create procedure dbo.UP_Egs_CheckRecTable 
    @year int,
  	@month int 
  	as
declare @TableName varchar(21)
declare @createsql nvarchar(1000)
set @TableName='T_E_CardRecord_'+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 ,'+
		'[fRecType] [tinyint] NOT NULL DEFAULT (0),'+
		'[fAccountID] [varchar] (18) COLLATE Chinese_PRC_CI_AS NOT NULL ,'+
		'[fCardNo] [varchar] (12) COLLATE Chinese_PRC_CI_AS NOT NULL ,'+
		'[fRecTime] [datetime] NOT NULL ,'+
		'[fReceiveTime] [datetime] NOT NULL DEFAULT (getdate()),'+
		'[fPosID] [int] NOT NULL ,'+
		'[fDoorID] [int],'+
		'[fWarnExportID] [tinyint],'+
		'[fWarnImportID] [tinyint],'+
		'[fCReaderID] [int],'+
		'[fButtonID] [int],'+
		'[fDoorMagnetID] [int],'+
		'[fOperID] [int] NOT NULL ,'+
		'CONSTRAINT [PK_'+@TableName+'] PRIMARY KEY  CLUSTERED '+
		'('+
		'	[fKeyID]'+
		')  ON [PRIMARY]'+ 
	') ON [PRIMARY]'
--	print @createsql
	exec sp_executesql @createsql

	set @createsql= 'CREATE 
	  INDEX [FK_'+@TableName+'] ON [dbo].['+@TableName+'] ([fAccountID], [fRecTime])'
	exec sp_executesql @createsql
end
go


create procedure dbo.UP_Egs_GetCardRec 
    @RecType int,
  	@strWhere varchar(1000),
  	@BeginDate datetime,
  	@EndDate datetime 
  	as
declare @b_Year varchar(4)
declare @b_Month varchar(2)

set @b_Year=datename(yyyy,@BeginDate)
set @b_Month=datename(mm,@BeginDate)


declare @i int
declare @MonthCount int
declare @sql_table nvarchar(4000)
declare @CurrDate datetime
set @i=0
set @MonthCount=datediff(mm,@BeginDate,@EndDate)

declare @sType varchar(200)
set @sType=''
if @RecType<>0 
	set @sType= 'fRecType='+cast(@RecType as varchar(2))+' and '

declare @TableName varchar(21)
set @sql_table=''
while (@i<=@MonthCount)
begin
	set @CurrDate=dateadd(m,@i,@BeginDate)
	set @TableName='T_E_CardRecord_'+datename(yyyy,@CurrDate)+dbo.fn_FillZero(2,datename(mm,@CurrDate))
--	print @TableName
	if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].['+@TableName+']') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	begin
		if @sql_table<>'' set @sql_table=@sql_table+CHAR(10)+' UNION '+CHAR(10)
		set @sql_table=@sql_table+' SELECT '+@TableName+'.*, T_B_Employee.fName, T_B_Employee.fEmployeeCode, T_B_Pos.fPosName
		FROM '+@TableName+' INNER JOIN T_B_Employee ON 
	        '+@TableName+'.fAccountID = T_B_Employee.fAccountID and  '+@strWhere+'  LEFT OUTER JOIN T_B_Pos ON '+@TableName+'.fPosID=T_B_Pos.fPosID WHERE '+@sType+'  (fRecTime>='''+convert(varchar(19),@begindate,20)+''' and fRecTime<='''+convert(varchar(19),@enddate,20)+''')'
		+CHAR(10)+ ' UNION '+CHAR(10)+
		' SELECT '+@TableName+'.*, '''' as fName, '''' as fEmployeeCode, T_B_Pos.fPosName
		FROM '+@TableName+'  LEFT OUTER JOIN T_B_Pos ON '+@TableName+'.fPosID=T_B_Pos.fPosID WHERE '+@sType+'  (fRecTime>='''+convert(varchar(19),@begindate,20)+''' and fRecTime<='''+convert(varchar(19),@enddate,20)+''' and fAccountID=''01999999'')'
	end
	set @i=@i+1
end
exec sp_executesql @sql_Table
--print @sql_Table
go


create procedure dbo.UP_InsertCardRec 
      @CardNo varchar(12),
  	  @RecordedTime datetime,
  	  @PosID int,
  	  @OperID int,
  	  @RecordType int = 1,
  	  @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

Set @ErrAccID = '00000000'
select @AccountID=fAccountID from T_B_Cards where fSerialNo=@CardNo
select @AccountID=fAccountID from T_B_CardInfo where fCard_State <>2 and fPhysicalNo = @CardNo   --2015-6-18 LFF ADD 

/*
if @AccountID is null 
begin
  select @AccountID = fAccountID from T_B_CardHis where fSerialNo = @CardNo 
end
*/
if @AccountID is null set @AccountID=@ErrAccID

set @b_Year=datename(yyyy,@RecordedTime)
set @b_Month=datename(mm,@RecordedTime)

exec UP_CheckRecTable @b_Year,@b_Month

declare @sql_table nvarchar(4000)

set @sql_table='if not exists (select * from T_A_CardRecord_'+@b_Year+@b_Month+' where fAccountID='''+@AccountID+''' and convert(varchar(19),fRecordedTime,20)='''+convert(varchar(19),@RecordedTime,20)+''')   '
set @sql_table=@sql_table + 'INSERT INTO T_A_CardRecord_'+@b_Year+@b_Month+
	' Values('+cast(@RecordType as varchar(2))+','''+
	@AccountID+''','''+@CardNo+''','''+
	convert(varchar(19),@RecordedTime,20)+''',GetDate(),'+
	cast(@PosID as varchar(5))+','''+cast(@OperID as varchar(5))+''')'

--print @sql_table
exec sp_executesql @sql_Table
select @Ret = cast(@@IDENTITY as varchar(10)) + '|T_A_CardRecordPic_'+@b_Year+@b_Month;   --插入的的序号,用于流水记录于照片记录对应
if @Ret is null
  Set @Ret = '0|T_A_CardRecordPic_'+@b_Year+@b_Month;
if exists (select fPosID from T_B_Pos where fPosID=@PosID and fPosType in (0,9))
if @RecordType in (1,9)
begin
   update T_B_PosDayRecs set fRecCount = fRecCount+1, fLastRecTime=getdate()
                     where fKeyID =  convert(varchar(20),@RecordedTime,112)+cast(@PosID as varchar(5))
   if @@rowcount = 0
     insert into T_B_PosDayRecs(fKeyID,fPosID,fRecDate,fRecCount, fLastRecTime) values(convert(varchar(20),@RecordedTime,112)+cast(@PosID as varchar(5)),@PosID,@RecordedTime,1,getdate())
end
else begin
   update T_B_PosDayRecs set fErrCount = fErrCount+1, fLastRecTime=getdate()
                     where fKeyID =  convert(varchar(20),@RecordedTime,112)+cast(@PosID as varchar(5))
   if @@rowcount = 0
     insert into T_B_PosDayRecs(fKeyID,fPosID,fRecDate,fErrCount, fLastRecTime) values(convert(varchar(20),@RecordedTime,112)+cast(@PosID as varchar(5)),@PosID,@RecordedTime,1,getdate())
end
go


create procedure dbo.UP_Egs_InsertCardRec 
    @CardNo varchar(12),
  	@RecTime datetime,
  	@PosID int,
  	@DoorID int,
  	@WarnExportID int,
  	@WarnImportID int,
  	@CReaderID int,
  	@ButtonID int,
  	@DoorMagnetID int,
  	@OperID int,
  	@RecType int = 1 
  	as
declare @AccountID varchar(18)
declare @TrueCardNo varchar(18)
declare @b_Year varchar(4)
declare @b_Month varchar(2)
declare @iParam int
declare @CardClass bigint
declare @ErrAccID varchar(20) --无效账号 默认由原来的01999999修改为00000000

Set @ErrAccID = '00000000'

select @iParam=isnull(fParamValue,0) from T_B_SysParam where fParamName='CardClass'
if @iParam=0 
   set @CardClass=4294967295
else
   set @CardClass=16777215
 
select @AccountID=fAccountID, @TrueCardNo=fSerialNo from T_B_Cards where fSerialNo = @CardNo 
select @AccountID=fAccountID, @TrueCardNo=fPhysicalNo from T_B_CardInfo where fCard_State <>2 and fPhysicalNo = @CardNo   --2015-6-18 LFF ADD 


if @AccountID is null 
begin
  select @AccountID = fAccountID from T_B_CardHis where fSerialNo = @CardNo
end

if @AccountID is null set @AccountID=@ErrAccID

set @b_Year=datename(yyyy,@RecTime)
set @b_Month=datename(mm,@RecTime)

exec UP_Egs_CheckRecTable @b_Year,@b_Month

declare @sql_table nvarchar(4000)

set @sql_table='if not exists (select * from T_E_CardRecord_'+@b_Year+@b_Month+' where fAccountID='''+@AccountID+''' and convert(varchar(19),fRecTime,20)='''+convert(varchar(19),@RecTime,20)+''' and fRecType='''+cast(@RecType as varchar(3))+''')   '
set @sql_table=@sql_table+ 'INSERT INTO T_E_CardRecord_'+@b_Year+@b_Month+
	' Values('+cast(@RecType as varchar(3))+','''+
	@AccountID+''','''+@CardNo+''','''+
	convert(varchar(19),@RecTime,20)+''',GetDate(),'+
	cast(@PosID as varchar(5))+','+
	cast(@DoorID as varchar(3))+','+
	cast(@WarnExportID as varchar(3))+','+
	cast(@WarnImportID as varchar(3))+','+
	cast(@CReaderID as varchar(3))+','+
	cast(@ButtonID as varchar(3))+','+
	cast(@DoorMagnetID as varchar(3))+','''+cast(@OperID as varchar(5))+''')'
exec sp_executesql @sql_Table

declare @Ret varchar(50)
if @RecType=4
begin
	exec UP_InsertCardRec @TrueCardNo, @RecTime, @PosID, @OperID, 1, @Ret output
end

if @RecType in (3,8,9,10,11,19)
begin
   update T_B_PosDayRecs set fRecCount = fRecCount+1, fLastRecTime=getdate()
                     where fKeyID =  convert(varchar(20),getdate(),112)+cast(@PosID as varchar(5))
   if @@rowcount = 0
     insert into T_B_PosDayRecs(fKeyID,fPosID,fRecCount, fLastRecTime) values(convert(varchar(20),getdate(),112)+cast(@PosID as varchar(5)),@PosID,1,getdate())
end
else begin
   update T_B_PosDayRecs set fWarnCount = fWarnCount+1, fLastRecTime=getdate()
                     where fKeyID =  convert(varchar(20),getdate(),112)+cast(@PosID as varchar(5))
   if @@rowcount = 0
     insert into T_B_PosDayRecs(fKeyID,fPosID,fWarnCount, fLastRecTime) values(convert(varchar(20),getdate(),112)+cast(@PosID as varchar(5)),@PosID,1,getdate())
end
go


create procedure dbo.UP_Egs_State_Detail 
    @CheckDate datetime,
  	@CheckTime datetime,
  	@deptcode varchar(30),
  	@jobroom varchar(2),
  	@sname varchar(20),
  	@cardno varchar(12),
  	@empcode varchar(20) 
  	as
declare @dcode varchar(50)
declare @room varchar(50)
declare @name varchar(50)
declare @cno varchar(50)
declare @ecode varchar(50)
DECLARE @strB varchar(19)
SET @strB=datename(yyyy, @CheckDate)+'-'+datename(mm, @CheckDate)+'-'+datename(dd, @CheckDate)+' '+datename(hh, @CheckTime)+':'+datename(mi, @CheckTime)+':'+datename(ss, @CheckTime)
if @deptcode <>'' begin set @dcode=' and e.fdept='''+@deptcode+'''' end else begin set @dcode=''  end
if @jobroom <>'' begin set @room=' and e.fjob='''+@jobroom+'''' end else begin set @room='' end
if @sname <> '' begin set @name=' and e.fname like ''%'+@sname+'%''' end else begin set @name='' end
if @cardno <> '' begin set @cno=' and e.fcardno='''+@cardno+'''' end else begin set @cno='' end
if @empcode <> '' begin set @ecode=' and e.femployeecode='''+@empcode+''''  end  else begin set @ecode='' end
declare @i int
declare @MonthCount int
declare @sql_table nvarchar(4000)
declare @CurrDate datetime
set @i=0
set @MonthCount=datediff(mm,@CheckDate,@CheckDate)

declare @TableName varchar(21)
set @sql_table=''

while (@i<=@MonthCount)
begin
	set @CurrDate=dateadd(m,@i,@CheckDate)
	set @TableName='T_E_CardRecord_'+datename(yyyy,@CurrDate)+dbo.fn_FillZero(2,datename(mm,@CurrDate))
--	print @TableName
	if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].['+@TableName+']') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	begin
		if @sql_table<>'' set @sql_table=@sql_table+CHAR(20)+' UNION '+CHAR(20)
		set @sql_table=@sql_table+'SELECT d.fposname as 打卡机,c.fdoorname as 门名,e.fname as 姓名,e.fdeptname as 班级,e.fjobname as 寝室,e.femployeecode as 学号,e.fcardno as 卡号,'+
		'case when b.freaderclass=1 then ''在'' '+
		'when b.freaderclass=5 then ''在'' '+
		'when b.freaderclass=9 then ''在'' '+
		'when b.freaderclass=13 then ''在'' else ''不在'' end as ''人员状态'','+
		'max(a.frectime) as 打卡时间 '+
		'FROM '+@TableName+' a,t_E_cardreader b,t_E_door c,t_B_pos d,v_B_EGS_employees e '+
		'where a.fposid=b.fposid and a.fdoorid=b.fdoorid and a.fcreaderid=b.freaderid and a.fposid=c.fposid '+
		'and a.fdoorid=c.fdoorid and a.fposid=d.fposid  and a.frectype=1 and b.freaderclass in (1,2,5,6,9,10,13,14) '+
		'and a.frectime<'''+@strB+' '+@dcode+ @room+@name+@cno+@ecode+''' group by d.fposname,c.fdoorname,e.fname,e.fdeptname,e.fjobname,'+
		'e.femployeecode,e.fcardno,b.freaderclass'
 
end
	set @i=@i+1
end
exec sp_executesql @sql_Table
--print @sql_Table
go


create procedure dbo.UP_Egs_State_Specific 
    @BeginDate datetime,
  	@EndDate datetime,
  	@BeginTime datetime,
  	@EndTime datetime,
  	@deptcode varchar(30),
  	@jobroom varchar(2),
  	@sname varchar(20),
  	@cardno varchar(12),
  	@empcode varchar(20) 
  	as
declare @dcode varchar(50)
declare @room varchar(50)
declare @name varchar(50)
declare @cno varchar(50)
declare @ecode varchar(50)
DECLARE @strB varchar(19)
DECLARE @strE varchar(19)
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)
if @deptcode <>'' begin set @dcode=' and e.fdeptcode='''+@deptcode+'' end else begin set @dcode=''  end
if @jobroom <>'' begin set @room=' and e.fjob='''+@jobroom+'' end else begin set @room='' end
if @sname <> '' begin set @name=' and e.fname like ''%'+@sname+'%''' end else begin set @name='' end
if @cardno <> '' begin set @cno=' and e.fcardno='''+@cardno+'' end else begin set @cno='' end
if @empcode <> '' begin set @ecode=' and e.femployeecode='''+@empcode+''  end  else begin set @ecode='' end
declare @i int
declare @MonthCount int
declare @sql_table nvarchar(4000)
declare @CurrDate datetime
set @i=0
set @MonthCount=datediff(mm,@BeginDate,@EndDate)

declare @TableName varchar(21)
set @sql_table=''

while (@i<=@MonthCount)
begin
	set @CurrDate=dateadd(m,@i,@BeginDate)
	set @TableName='T_E_CardRecord_'+datename(yyyy,@CurrDate)+dbo.fn_FillZero(2,datename(mm,@CurrDate))
--	print @TableName
	if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].['+@TableName+']') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	begin
		if @sql_table<>'' set @sql_table=@sql_table+CHAR(20)+' UNION '+CHAR(20)
		set @sql_table=@sql_table+' SELECT d.fposname as 打卡机,c.fdoorname as 门名,e.fname as  姓名,e.fdeptname as 班级,e.fjobname as 寝室,e.femployeecode as 学号,e.fcardno as 卡号,'+
		'case when b.freaderclass=1 then ''进门'' when b.freaderclass=5 then ''进门'' when b.freaderclass=9 then ''进门'' when b.freaderclass=13 then ''进门'' else ''出门'' end as ''打卡状态'',a.frectime  as ''打卡时间'' '+
		 'FROM '+@TableName+' a,t_E_cardreader b,t_E_door c,t_B_pos d,v_B_EGS_employees e '+
		'where a.fposid=b.fposid and a.fdoorid=b.fdoorid and a.fcreaderid=b.freaderid '+
		'and a.fposid=c.fposid and a.fdoorid=c.fdoorid '+
		'and a.fposid=d.fposid  and a.frectype=1 and b.freaderclass in (1,2,5,6,9,10,13,14)  and a.frectime>'''+@strB+''' and a.frectime<'''+@strE+'''' +@dcode+ @room+@name+@cno+@ecode
end
	set @i=@i+1
end
exec sp_executesql @sql_Table
--print @sql_Table
go


create procedure dbo.UP_EmpRuleHistory 
      @AccountID     varchar(18),  -- 帐号
      @GroupID       varchar(20),  --分组编号
      @OperID        varchar(40),   --操作员
      @Remark        varchar(100) 
      as
insert into T_E_EmpRuleHistory(fAccountID, fPhysicalNo, fGroupID, fPosID, fCtrlRuleID, 
           fDoor1Rule, fDoor2Rule,fDoor3Rule, fDoor4Rule, 
           fOperID, fRemark)
            select a.fAccountID, fSerialNo, @GroupID, fPosID, fCtrlRuleID, fDoor1Rule, fDoor2Rule, fDoor3Rule, fDoor4Rule,@OperID,@Remark from (           
			select fAccountID, fPosID, fEnable, fCtrlRuleID, fDoor1Rule, fDoor2Rule, fDoor3Rule, fDoor4Rule, fPass, fDeadLine,fXGEnable, 1 as fRuleType 
			from T_E_EmpRule where fAccountID = @AccountID --and ((fDoor1Rule<>0)or (fDoor2Rule<>0) or (fDoor3Rule<>0) or (fDoor4Rule<>0) )            
			) a  inner join T_B_Employee e on a.fAccountID = e.fAccountID
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


create procedure dbo.UP_EmpTopRecord 
    @RecType int,
   	@Date datetime,
   	@AccountID varchar(8),
   	@RecCount int 
   	as
BEGIN
	DECLARE @BeginTime datetime,
	        @EndTime datetime

	DECLARE @STRSQL nvarchar(4000),
	        @Where nvarchar(1000),
	        @iRet int,
	        @sRet varchar(300)
	        
	EXEC UP_R_CheckTime @Date, @Date, 1, @iRet output, @sRet output
	if @sRet = '' or @iRet = -9999
	begin
      SELECT '查询表无效-查询表范围超期' AS [返回信息] 
	  Return --如果表不存在，直接退出
	end
	
	IF @RecType=99 
		SET @Where=''
	ELSE
		SET @Where=' AND R.fRecType='+CAST(@RecType AS VARCHAR(3))
	
	SET @STRSQL=
		' SELECT TOP '+CAST(@RecCount AS VARCHAR(2))+' 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 '+@sRet+' 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 
		WHERE R.fAccountID='''+@AccountID+''' '+ @Where + ' 
		ORDER BY R.fCreateTime DESC '
	print @strsql
	exec sp_executesql @strsql
END
go


create procedure dbo.UP_GetCardRecord 
    @strWhere varchar(1000),
  	@BeginDate datetime,
  	@EndDate datetime 
  	as
declare @b_Year varchar(4)
declare @b_Month varchar(2)

set @b_Year=datename(yyyy,@BeginDate)
set @b_Month=datename(mm,@BeginDate)


declare @i int
declare @MonthCount int
declare @sql_table nvarchar(4000)
declare @CurrDate datetime
set @i=0
set @MonthCount=datediff(mm,@BeginDate,@EndDate)

declare @tmpWhere varchar(500)

declare @TableName varchar(21)
set @sql_table=''
while (@i<=@MonthCount)
begin
	set @CurrDate=dateadd(m,@i,@BeginDate)
	set @TableName='T_A_CardRecord_'+datename(yyyy,@CurrDate)+dbo.fn_FillZero(2,datename(mm,@CurrDate))

	set @tmpWhere=''
	if (@strWhere<>'')
	begin 
		set @tmpWhere = +@TableName+'.fAccountID in (SELECT fAccountID FROM T_B_Employee WHERE '+@StrWhere+') and ' 
	end

	if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].['+@TableName+']') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	begin
		if @sql_table<>'' set @sql_table=@sql_table+CHAR(10)+' UNION '+CHAR(10)
		set @sql_table=@sql_table+' SELECT '+@TableName+'.*, T_B_Employee.fName, T_B_Employee.fEmployeeCode, T_B_Pos.fPosName
		FROM '+@TableName+' INNER JOIN T_B_Employee ON 
	        '+@TableName+'.fAccountID = T_B_Employee.fAccountID LEFT OUTER JOIN T_B_Pos ON '+@TableName+'.fPosID=T_B_Pos.fPosID 
		WHERE '+@tmpWhere+'(fRecordedTime>='''+convert(varchar(19),@begindate,20)+''' and fRecordedTime<='''+convert(varchar(19),@enddate,20)+''')'
	end
	set @i=@i+1
end
exec sp_executesql @sql_Table
--print @sql_Table
go


create procedure dbo.UP_GetCardRecordByAccount 
    @AccountID varchar(18),
  	@BeginDate datetime,
  	@EndDate datetime 
  	as
declare @b_Year varchar(4)
declare @b_Month varchar(2)

set @b_Year=datename(yyyy,@BeginDate)
set @b_Month=datename(mm,@BeginDate)


declare @i int
declare @MonthCount int
declare @sql_table nvarchar(4000)
declare @CurrDate datetime
set @i=0
set @MonthCount=datediff(mm,@BeginDate,@EndDate)

declare @TableName varchar(21)
set @sql_table=''
while (@i<=@MonthCount)
begin
	set @CurrDate=dateadd(m,@i,@BeginDate)
	set @TableName='T_A_CardRecord_'+datename(yyyy,@CurrDate)+dbo.fn_FillZero(2,datename(mm,@CurrDate))
	if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].['+@TableName+']') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	begin
		if @i>0 set @sql_table=@sql_table+CHAR(10)+' UNION '+CHAR(10)
		set @CurrDate=dateadd(m,@i,@BeginDate)
		set @sql_table=@sql_table+' SELECT * FROM T_A_CardRecord_'+datename(yyyy,@CurrDate)+datename(mm,@CurrDate)+' WHERE fAccountID='''+@AccountID+''' and (fRecordedTime>='''+convert(varchar(19),@begindate,20)+''' and fRecordedTime<='''+convert(varchar(19),@enddate,20)+''')'
	end
	set @i=@i+1
end
if @sql_Table<>''
	exec sp_executesql @sql_Table
else
	exec sp_executesql  N'SELECT 0 as [fKeyID], 0 as [fRecordedType], null as [fAccountID], null as [fCardNo], 0 as [fRecordedTime], 0 as [fReceiveTime], 0 as [fPosID], 0 as [fOperID] where 1<>1'
--print @sql_Table
go


create procedure dbo.UP_GetNewAccountID 
as
declare @MaxID_Employee bigint
declare @MaxID_Param bigint
SELECT @MaxID_Employee=MAX([fAccountID]) FROM T_B_Employee
SELECT @MaxID_param=[fParamValue] FROM [T_B_SysParam] WHERE [fParamName]='MaxAccountID'

if isnull(@MaxID_Employee,0)=0 
	SET @MaxID_Employee=0
if (@MaxID_param<@MaxID_Employee) or (isnull(@MaxID_param,0)=0)
	UPDATE [T_B_SysParam] SET [fParamValue] =@MaxID_Employee WHERE [fParamName]='MaxAccountID'


UPDATE [T_B_SysParam] SET [fParamValue] =cast([fParamValue] as bigint) +1 WHERE [fParamName]='MaxAccountID'
SELECT [fParamValue] as fMaxAccountID FROM [T_B_SysParam] WHERE [fParamName]='MaxAccountID'
go


create procedure dbo.UP_GetOffDays 
@AccountID varchar(18) 
as
DECLARE @fCheckSystemCode varchar(4)
	SELECT @fCheckSystemCode=fCheckSystem FROM T_B_Employee WHERE fAccountID=@AccountID
	
	SELECT fOffDayIsWeek, fOffDay FROM T_A_CheckRule WHERE fCheckSystemCode=@fCheckSystemCode
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


create procedure dbo.UP_InsertOffLineRecord 
    @PurseID INT,						--钱包编号
 	@FlowType INT,						--流水类型
 	@RecType INT,						--交易类型
 	@UserCardID VARCHAR(16),			--用户卡号(物理卡号/应用序列号)
 	@PosID INT,							--交易终端号
 	@CreateTime DATETIME,				--交易时间
 	@RecvTime DATETIME,					--入库时间
 	@Amount money ,				--交易额
 	@Discount money ,			--折扣额
 	@SourceID INT,						--来源
 	@OperID INT,						--操作员编号
 	@OffTranNo INT,						--卡脱机交易序号
 	@PosTranNo INT,						--终端交易序号
 	@fRecKey VARCHAR(200),				--数据校验Key值
 	@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 money ,		--交易前余额
		@Balance money ,			--交易后余额
		@OLTransNo INT,					--联机交易次数
		@SettleTime DATETIME,			--入账时间
		@Fraptime DATETIME,				--结算时间
		@CardState INT,					--卡片状态
		@iSucc INT,						--写预存流水状态 
		@ErrAccID VARCHAR(20),			--无效账号 默认由原来的01999999修改为00000000
		@ErrCardID VARCHAR(20),			--无效逻辑卡号
		@Fee1 money ,			--其他费用1(手续费)
		@Fee2 money ,			--其他费用2(卡费)
		@Fee3 money ,			--其他费用3(押金)
		@Fee4 money ,			--其他费用4(管理费)
		@TaskID INT,
		@Record_ID VARCHAR(10)
		

	/*临时变量定义*/
	DECLARE 
		@PTime VARCHAR(100),
		@bPrint BIT
	SET @Ret = 0	 --赋值返回值初始值	
	SET @bPRINT = 1  --是否显示调试信息（用于显示各个阶段耗时） 
	SET @ErrAccID = '00000000'
	SET @ErrCardID = '00000000'  	
	SET @CardState=0
	SET @SettleTime = @CreateTime		--联机流水以流水发生时间下账
	SET @Fee1=0
	SET @Fee2=0
	SET @Fee3=0
	SET @Fee4=0
	SET @TaskID=0
	--根据卡号获取账户信息
	/*
	1.在卡表中查询 T_B_Cards
	2.在账户卡历史表中查询 T_B_CardHis
	*/
	--1.在卡表中查询卡号对应帐号
	SELECT @AccountID=C.fAccountID,@CardState=fCardState,@DeptCode=E.fDept 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 @FkTime >= fBeginTime and @FkTime < fEndTime
		IF @@rowcount=0 
		BEGIN
			SET @AccountID=@ErrAccID	
		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+','+Cast(@FkTime as varchar(5))+cast(@RecType as varchar(3))
			SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime 
		END 
		EXEC SP_SETCardHis @AccountID, @UserCardID,@DeptCode,@FkTime,@RecType
	END
	*/
	
	/*根据交易时间获取交易时段*/
	SELECT @MealID=fMeal_Id FROM T_B_MealSet WHERE (CAST(fBegin_Time as time)<CAST(@CreateTime as time)) AND (CAST(fEnd_Time as time)>CAST(@CreateTime as time))
	/*根据终端号来获取工作站号*/
	SELECT @StationID=SUBSTRING(fSiteID,1,2) FROM T_B_Pos WHERE fPosID=@PosID
	
	--在钱包应用表中查找钱包信息
	SELECT @OldMoney=ISNULL(fBalance,0), @OLTransNo=ISNULL(fTransNo+1,1) FROM T_B_Purses WHERE fAccountID=@AccountID AND fPurseCode=@PurseID
	IF @@ROWCOUNT=0 
	BEGIN
		SET @OldMoney=0
		SET @OLTransNo=1
		PRINT '----*****----'
		PRINT @OldMoney
		PRINT @OLTransNo
		PRINT '----*****----'
	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, @WtPinCard,@WtDelCard, @WtDisabledPurse )
	BEGIN
		SET @Balance=@OldMoney-@Amount-@Fee1
	END
	ELSE BEGIN
		SET @Balance=@OldMoney+@Amount
	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)
	/*检查或创建流水表*/
	--EXEC SP_Wst_CheckRecTable @CreateTime, 0, @TableName_C output
	EXEC SP_Wst_CheckRecTable @CreateTime, 1, @TableName_S 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) 
			 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(@PosTranNo AS VARCHAR(10)) + ''', 
				''' + @MealID  + ''', 
				''' + @fRecKey + ''' ) ' 
		EXEC sp_executesql @TabSQL
		IF @@ERROR <> 0    
		BEGIN 
			SET @Ret = '3' 
			GOTO returnCommit
		END
		ELSE BEGIN
			SET @Ret = '0' 
			GOTO returnCommit
		END		
	END
	ELSE BEGIN		
		/*
	   流水按月分表存储，判断重复由表的联合主键判断
	   */
		IF @bPRINT = 1
		BEGIN
			PRINT '-----------判断重复插入流水------------'
			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,
				fSiteID,
				fDeptCode,
				fOperID,
				fMealID,
				fTaskID,
				fRecKey) 
			 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)) + ''', ''' +  
				@Stationid + ''', ''' + 
				@DeptCode + ''', ''' + 
				CAST(@OperID AS VARCHAR(5)) + ''', ''' + 			
				@MealID  + ''', '+
				CAST(@TaskID AS VARCHAR(5))+ ', ''' +  
				@fRecKey + ''' ) ' 
		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
		IF @@ERROR <> 0    
		BEGIN 
			SET @Ret = '3' 
			GOTO returnCommit
		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,
						@WtSubClear)  --正常交易类数据更新
		BEGIN			
			UPDATE T_B_Purses 
			SET fBalance = @Balance,
				fTransNo = @OLTransNo				
			WHERE fAccountID=@AccountID and fPurseCode = @PurseID
		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_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
	
	/*
	汇总数据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、操作类型、费用类型、应用号
		
		IF @@rowcount = 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
			IF @@rowcount = 0
				INSERT INTO T_B_PosDayRecs(fKeyID,fPosID,fRecDate,fSaveCount,fSaveSum, fLastRecTime) 
				VALUES(@fKey_PDR ,@PosID,@SETtletime,1,@Amount,@RecvTime)  	
		END
		ELSE IF (@RecType = @WtTake) --取款
		BEGIN
			UPDATE T_B_PosDayRecs SET fTakeCount = fTakeCount+1, fTakeSum = fTakeSum + @Amount, fLastRecTime=@SETtletime
								  WHERE fKeyID = @fKey_PDR
			IF @@rowcount = 0
				INSERT INTO T_B_PosDayRecs(fKeyID,fPosID,fRecDate,fTakeCount,fTakeSum, fLastRecTime) 
				VALUES(@fKey_PDR ,@PosID,@SETtletime,1,@Amount,@RecvTime)  
		END  
		ELSE IF (@RecType = @WtRecovery) --纠错
		BEGIN
			UPDATE T_B_PosDayRecs SET fPutRightCount = fPutRightCount+1, fPutRightSum = fPutRightSum + @Amount, fLastRecTime=@SETtletime
								  WHERE fKeyID = @fKey_PDR
			IF @@rowcount = 0
				INSERT INTO T_B_PosDayRecs(fKeyID,fPosID,fRecDate,fPutRightCount,fPutRightSum, fLastRecTime) 
				VALUES(@fKey_PDR ,@PosID,@SETtletime,1,@Amount,@RecvTime)  
		END  
		ELSE --0消费 17脱机消费
		BEGIN
			UPDATE T_B_PosDayRecs SET fRecCount = fRecCount+1, fConsSum = fConsSum + @Amount, fLastRecTime=@SETtletime
								  WHERE fKeyID = @fKey_PDR
			IF @@rowcount = 0
				INSERT INTO T_B_PosDayRecs(fKeyID,fPosID,fRecDate,fRecCount,fConsSum, fLastRecTime)
				VALUES (@fKey_PDR ,@PosID,@SETtletime,1,@Amount,@RecvTime)
		END
	END	
		
	IF @bPRINT = 1
	BEGIN
		PRINT '-----------更新POS机最后更新时间------------'
		SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime
	END  
	UPDATE T_B_Pos SET fLastRecTime = @CreateTime WHERE fPosID = @PosID
	
	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 money 
		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、操作类型、费用类型、应用号
				
		IF @@rowcount = 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 '-----------汇总数据4-更新用户交易汇总信息------------'
		SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime
	END	
	DECLARE @TableName_SE VARCHAR(20)
	DECLARE @WhereUp VARCHAR(100)
	DECLARE @WhereInField VARCHAR(100)
	DECLARE @WhereInValue VARCHAR(100)
	EXEC SP_Wst_CheckSumEmpTable @CreateTime, @TableName_SE output
	
	IF @RecType IN (@WtCons, @WtOfflineWater)	
	BEGIN
		IF @Discount=0
		BEGIN
			SET @WhereUp =	'fConsCount = fConsCount + 1, fConsMoney = fConsMoney + ' + CAST(@Amount AS VARCHAR(18)) 
			SET @WhereInField = 'fConsCount, fConsMoney'
			SET @WhereInValue = '1, '+CAST(@Amount AS VARCHAR(18))+','
		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)) 
			SET @WhereInField = 'fConsCount, fConsMoney, fDiscountCount, fDiscountMoney'
			SET @WhereInValue = '1, '+CAST(@Amount AS VARCHAR(18))+',1 '+CAST(@Discount AS VARCHAR(18))+','		
		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)
	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 
	*/
	SET @TabSQL=
		'UPDATE ['+@TableName_SE+'] 
		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)) + ', ' + 
			'fNewBalance = '+CAST(@Balance AS VARCHAR(18)) + 
		 ' 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 
	DECLARE @UpdateRecCount INT
	SET @UpdateRecCount=@@rowcount
	IF @@ERROR <> 0    
	BEGIN 
		SET @Ret = '3' 
		GOTO returnCommit 
	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 = '3' 
		GOTO returnCommit 
	END  
	
	IF @bPRINT = 1
	BEGIN
		PRINT '-----------汇总数据5-更新用户每日餐次消费汇总信息------------'
		SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime
	END	
	DECLARE @TableName_CE VARCHAR(20)
	DECLARE @WhereUp_CE VARCHAR(100)
	DECLARE @WhereInField_CE VARCHAR(100)
	DECLARE @WhereInValue_CE VARCHAR(100)
	DECLARE @MealField VARCHAR(6)
	EXEC SP_Wst_CheckConsEmpTable @CreateTime, @TableName_CE output
	SET @MealField = 'fMeal'+CAST(CAST(@MealID AS INT) AS VARCHAR(1))
	IF @RecType IN (@WtCons, @WtOfflineWater)	
	BEGIN
		SET @WhereUp_CE = @MealField+'Count = '+@MealField+'Count + 1, '+@MealField+'Money = '+@MealField+'Money + ' + CAST(@Amount AS VARCHAR(18)) 
		SET @WhereInField_CE = @MealField+'Count, '+@MealField+'Money'
		SET @WhereInValue_CE = '1, '+CAST(@Amount AS VARCHAR(18))+','
	END
		
	SET @WhereUp_CE=ISNULL(@WhereUp_CE,'')
	SET @WhereInField_CE=ISNULL(@WhereInField_CE,'')
	SET @WhereInValue_CE=ISNULL(@WhereInValue_CE,'')
	
	SET @TabSQL=
		'UPDATE ['+@TableName_CE+'] 
		SET '+@WhereUp_CE+	', ' + 
			'fDayMoney = fDayMoney + '+CAST(@Amount AS VARCHAR(18)) + ', ' + 
			'fDayCount = fDayCount + 1 '+
		 ' 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 = '3' 
		GOTO returnCommit 
	END  
	PRINT '@UpdateRecCount - '+CAST(@UpdateRecCount AS VARCHAR(1))
	IF @UpdateRecCount = 0	
	BEGIN
		SET @TabSQL=
			'INSERT INTO ['+@TableName_CE+'] 
				(fKeyID,
				fAccountID,
				fDate,
				fPurseID,
			'+@WhereInField_CE+',
				fDayMoney,
				fDayCount) 
			 VALUES( 
				''' + @fKey_CE + ''', ''' + 
				@AccountID + ''', ''' + 
				@sDate + ''', ' +  
				CAST(@PurseID AS VARCHAR(4)) + ', ' +
				@WhereInValue + 		
				CAST(@Amount AS VARCHAR(18)) + ',1) '  
		IF @bPRINT = 1
		BEGIN	
			PRINT @TabSQL
			SELECT @Ptime = CONVERT(VARCHAR(100), GETDATE(), 13)  PRINT @Ptime 
		END 
		EXEC sp_executesql @TabSQL 
	END
	--将记录保存到其他工作站
  declare @CStationID	 varchar(2)
  declare  cur_Station cursor for  
  select distinct fStation_ID from t_b_station where fStation_ID<>@StationID 
  open cur_Station  
  fetch next  from cur_Station into @CStationID 
 
  while @@fetch_status = 0  
  begin  
	
	exec SP_Cash_CheckRecTable @CStationID
	
	set @TabSQL=' if not  exists (select  * from T_C_Cashdata'+@CStationID+' where fAccountID='''+@AccountID+''')
	            insert into T_C_Cashdata'+@CStationID+'([fAccountID],[fSerialNo],[fPurseID],[fConsTime],[fRecType],[fAmount],[fStationid],[fSettleTime])
	            values('''+@AccountID+''','''+@UserCardID+''','+CAST(@PurseID AS VARCHAR(4)) +','''+CONVERT(VARCHAR(40), @CreateTime, 21)+''',
	            '+CAST(@RecType AS VARCHAR(2))+','+ CAST(@Amount AS VARCHAR(18))+','''+@CStationID+''','''+CONVERT(VARCHAR(40), @SETtletime, 21)+''')'
	print @TabSQL
	exec(@TabSQL) 
    fetch next from cur_Station into @CStationID
  end  
  close cur_Station  
  deallocate  cur_Station  
	IF @@ERROR <> 0    
	BEGIN 
		SET @Ret = '3' 
		GOTO returnCommit 
	END  
	
	ReturnCommit:
		Commit Tran
		Return
	ReturnErr: 
		SET @Ret = '2'
		IF @@trancount > 0
			Rollback Tran 
		Return
END
go


create procedure dbo.UP_InsertOnLineRecord 
   @PurseID INT,      --钱包编号        
   @FlowType INT,      --流水类型        
   @RecType INT,      --交易类型        
   @UserCardID VARCHAR(16),   --用户卡号(物理卡号/应用序列号)        
   @PosID INT,       --交易终端号        
   @CreateTime DATETIME,    --交易时间        
   @RecvTime DATETIME,     --入库时间        
   @Amount money ,    --交易额        
   @Discount money ,   --折扣额        
   @SourceID INT,      --来源        
   @TaskID INT,      --任务编号        
   @OperID INT,      --操作员编号         
   @Fee1 money ,    --其他费用1(手续费)        
   @Fee2 money ,    --其他费用2(卡费)        
   @Fee3 money ,    --其他费用3(押金)        
   @Fee4 money ,    --其他费用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 money ,  --交易前余额        
  @Balance money ,   --交易后余额        
  @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 money         
  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_ADD_3 创建存储过程 - 人员消费数据汇总月表，用于存放人员按月汇总的数据*/
create procedure [dbo].[SP_Wst_CheckSumEmpMonthTable]   
  @datetime datetime,  
  @Ret varchar(30) output   
as 
begin 
  declare @TableName varchar(25)  
  declare @Sql nvarchar(4000)  
  declare @PRI nvarchar(300)  
  declare @EndSQL nvarchar(300)  
  
  select @TableName='T_C_SumEmpMonth_' + CONVERT(varchar(6), @datetime, 112) 
  if exists(select * from dbo.sysobjects where id = OBJECT_ID(@TableName) and OBJECTPROPERTY(id, 'IsUserTable') = 1)
  begin
    select @Ret = @TableName 
    return
  end
    
  select @PRI =  
				' PRIMARY KEY CLUSTERED   
				(  
					[fKeyID] ASC  
				)) ON [PRIMARY] '  
 
  --非聚集索引 
  select @EndSQL = '
          CREATE NONCLUSTERED INDEX [FK_Sett_' + @TableName +'] ON ' + @TableName + '   
					       ([fKeyID] ASC,  
							      [fDataYM] ASC,  
							      [fAccountID] ASC,  
							      [fPurseID] ASC )' 

   set @Sql=  
			' CREATE TABLE ['+@TableName+'] (  
				[fKeyID] [varchar](18) NOT NULL,
				[fDataYM] [varchar](8) NOT NULL,
				[fAccountID] [varchar](8) NOT NULL,								
				[fPurseID] [int] NOT NULL,
				[fOldBalance] [Money] NOT NULL DEFAULT (0.00),
				[fConsCount] [int] NOT NULL DEFAULT (0),
				[fConsMoney] [Money] NOT NULL DEFAULT (0.00),
				[fLimitConsCount] [int] NOT NULL DEFAULT (0),
				[fLimitConsMoney] [Money] NOT NULL  DEFAULT (0.00),
				[fSaveCount] [int] NOT NULL DEFAULT (0),
				[fSaveMoney] [Money] NOT NULL DEFAULT (0.00),
				[fTakeCount] [int] NOT NULL DEFAULT (0),
				[fTakeMoney] [Money] NOT NULL DEFAULT (0.00),
				[fSubCount] [int] NOT NULL DEFAULT (0),
				[fSubMoney] [Money] NOT NULL DEFAULT (0.00),
				[fClearCount] [int] NOT NULL DEFAULT (0),
				[fClearMoney] [Money] NOT NULL DEFAULT (0.00),
				[fPutRightCount] [int] NOT NULL DEFAULT (0),
				[fPutRightMoney] [Money] NOT NULL DEFAULT (0.00),
				[fDiscountCount] [int] NOT NULL DEFAULT (0),
				[fDiscountMoney] [Money] NOT NULL DEFAULT (0.00),
				[fFee1] [Money] NOT NULL DEFAULT (0.00),
				[fFee2] [Money] NOT NULL DEFAULT (0.00),
				[fFee3] [Money] NOT NULL DEFAULT (0.00),
				[fFee4] [Money] NOT NULL DEFAULT (0.00),
				[fNewBalance] [Money] NOT NULL DEFAULT (0.00), 
				[fAccountDate] [datetime] DEFAULT getdate(), 
        ' + @PRI  + @EndSQL  
  --print @Sql  
  exec(@Sql)  
  if @@error = 0  
    set @Ret = @TableName
  else
    Set @Ret = ''      
  Return 
end
go


/*PROC_ADD_4 创建存储过程 - 生成系统总表(月)数据，由一卡通服务程序跨月时调用*/
create PROCEDURE [dbo].[UP_Make_SysAccont_Month]
  @Year  varchar(4), --年，'YYYY'   
  @Month varchar(2), --月，'MM'
  @ReSumFlag bit,    --如果已有数据是否重新结算，0：不重新结算；1：重新结算
  @Ret varchar(50) output
AS          
BEGIN 
  declare @AccountDay int        --月结算日期,0：自然月；其余为财务月日期
  declare @CurrDataYM varchar(7) --本次数据年月
  declare @SuccCount int         --结算成功月次数
  
  set @AccountDay = 0
  select @AccountDay = fParamValue from T_B_SysParam where fParamName = 'SysMonthAccountDate' 
  
  if (@AccountDay < 0) or (@AccountDay > 28)  
  begin
    set @Ret = '0|设定财务结算日期非法'
    return
  end
  
  set @CurrDataYM = @Year + '-' + right('00'+ltrim(@Month),2)    
          
  declare @LastDataYM       varchar(7)    --最近一次数据年月
  declare @TempDataYM       varchar(7)    --临时数据年月变量
  declare @DataBDate        datetime      --数据开始日期
  declare @DataEDate        datetime      --数据结束日期
                
  declare @AccountCount     bigint = 0;   --现账户人数
  declare @AccountBalance   Money = 0.00; --现账户余额
  declare @ConsCount        bigint = 0;   --消费次数       
  declare @ConsMoney        Money = 0.00; --消费金额         
  declare @khCount          int;          --开户次数
  declare @KhMoney          Money = 0.00; --开户金额         
  declare @KhDpsit          Money = 0.00; --开户押金         
  declare @KhPndge          Money = 0.00; --开户手续费         
  declare @KhManage         Money = 0.00; --开户管理费         
  declare @ChCount          int = 0;      --撤户次数    
  declare @ChMoney          Money = 0.00; --撤户金额         
  declare @ChDpsit          Money = 0.00; --撤户押金         
  declare @ChPndge          Money = 0.00; --撤户手续费         
  declare @GsCount          int = 0;      --挂失次数    
  declare @GsPndge          Money = 0.00; --挂失手续费         
  declare @JgCount          int = 0;      --解挂次数    
  declare @JgPndge          Money = 0.00; --解挂手续费         
  declare @SvCount          int = 0;      --存款次数    
  declare @SvMoney          Money = 0.00; --存款金额         
  declare @SvPndge          Money = 0.00; --存款手续费         
  declare @TkCount          int = 0;      --取款次数    
  declare @TkMoney          Money = 0.00; --取款金额         
  declare @HkCount          int = 0;      --换卡次数    
  declare @HkPndge          Money = 0.00; --换卡手续费         
  declare @BkCount          int = 0;      --补卡次数    
  declare @BkMoney          Money = 0.00; --补卡金额         
  declare @BkPndge          Money = 0.00; --补卡手续费         
  declare @JcCount          int = 0;      --纠错次数    
  declare @JcMoney          Money = 0.00; --纠错金额         
  declare @SbCount          int = 0;      --补助次数    
  declare @SbMoney          Money = 0.00; --补助金额         
  declare @sbClrCount       int = 0;      --补助清零次数    
  declare @sbClrMoney       Money = 0.00; --补助清零金额
  declare @QCCount          int = 0;      --圈存次数    
  declare @QCMoney          Money = 0.00; --圈存金额         
  declare @QCBXCount        int = 0;      --圈存补写次数    
  declare @QCBXMoney        Money = 0.00; --圈存补写金额         
  
  declare @AccountCountJC   int = 0;      --现账户人数
  declare @AccountBalanceJC int = 0;      --原账户金额(计次)
  declare @ConsMoneyJC      int = 0;      --营业金额(计次)
  declare @SvCountJC        int = 0;      --存款人数(计次)       
  declare @SvMoneyJC        int = 0;      --存款金额(计次)       
  declare @TkCountJC        int = 0;      --取款人数(计次)       
  declare @TkMoneyJC        int = 0;      --取款金额(计次) 
  declare @JcCountJC        int = 0;      --纠错人数(计次)       
  declare @JcMoneyJC        int = 0;      --纠错金额(计次)
  declare @SbCountJC        int = 0;      --补助人数(计次)         
  declare @SbMoneyJC        int = 0;      --补助金额(计次) 
  declare @sbClrCountJC     int = 0;      --补助清除人数(计次)        
  declare @sbClrMoneyJC     int = 0;      --补助清除金额(计次)                
            
  SET NOCOUNT ON; 
  
  if exists(select * from T_R_SysAccount_Month where fDataYM = @CurrDataYM)
  begin          
				if @ReSumFlag = 1
				begin
						delete T_R_SysAccount_Month where fDataYM >= @CurrDataYM
				end
				else
				begin
				  set @Ret = '0|当月结算数据已经存在，选择不重新结算'
				  return 
				end          
  end       
  
  set @LastDataYM = ''
  select top 1 @LastDataYM = fDataYM, @AccountCount = fAccountCount, @AccountBalance = fAccountBalance,
               @AccountBalanceJC = fAccountBalanceJC 
    from T_R_SysAccount_Month 
   where fDataYM < @CurrDataYM 
   order by fDataYM desc
   
  if @LastDataYM = '' --没有任何结算数据时
  begin
    select top 1 @LastDataYM = CONVERT(varchar(7), dateadd(mm, -1, fdate), 120) from T_C_SUM_OPER
     order by fDate
  end
  
  if @LastDataYM = ''
  begin
    set @Ret = '0|没有任何可供结算的数据'
    return
  end
  
  set @TempDataYM = convert(varchar(7), DATEADD(mm, 1, (@LastDataYM + '-01 00:00:00')), 120) --最后结算月份的下一个月份
  set @SuccCount = 0  
  while @TempDataYM <= @CurrDataYM
  begin
				if @AccountDay = 0 --自然月
				begin
						set @DataBDate = @TempDataYM + '-01 00:00:00'
						set @DataEDate = DATEADD(mm, 1, @DataBDate)
						set @DataEDate = DATEADD(DD, -1, @DataEDate)
				end
				else
				begin
						if @AccountDay < 15
						begin
								set @DataBDate = @TempDataYM + '-' + RIGHT('00' + convert(varchar(3), @AccountDay), 2) + ' 00:00:00'
								set @DataEDate = DATEADD(mm, 1, @DataBDate)
								set @DataEDate = DATEADD(DD, -1, @DataEDate)      
						end
						else
						begin
								set @DataEDate = @TempDataYM + '-' + RIGHT('00' + convert(varchar(3), @AccountDay), 2) + ' 00:00:00'
								set @DataBDate = DATEADD(mm, -1, @DataEDate)
								set @DataBDate = DATEADD(dd, 1, @DataBDate)    
						end
				end
		  
				if datediff(dd, @DataEDate, getdate()) < 1
				begin
						--set @Ret = '0|未到结算时间不能结算'
						--return
						break
				end
		  
				print convert(varchar(20), @DataBDate, 120)
				print convert(varchar(20), @DataEDate, 120)
          
				select @ConsCount = ISNULL(SUM(fCount),0), @ConsMoney = ISNULL(SUM(fMoney),0) from T_C_SUM_Pos           
		 		where (fDate between @DataBDate and @DataEDate) 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),       -- 开户人数          
						@KhMoney = 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), -- 撤户人数          
						@ChMoney = ISNULL(SUM( (case when fTType in (7,25) and fCType = 0 then fMoney else 0 end) ), 0), -- 撤户金额          
						@ChDpsit = 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),       -- 存款手续费          
						@SvMoney = 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),       -- 取款人数          
						@TkMoney = 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),      -- 补卡人数          
						@BkMoney = 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),       -- 纠错人数          
						@JcMoney = 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),       -- 补助人数          
						@SbMoney = ISNULL(SUM( (case when fTType = 3 and fCType = 0 then fMoney else 0 end) ), 0),       -- 补助金额          
				            
						@SbClrCount = ISNULL(SUM( (case when fTType = 37 and fCType = 0 then fCount else 0 end) ), 0), -- 补助清零人数          
						@SbClrMoney = 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),      -- 圈存人数          
						@QCMoney = 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),    -- 圈存补写人数          
						@QCBXMoney = ISNULL(SUM( (case when fTType = 29 and fCType = 0 then fMoney else 0 end) ), 0)     -- 圈存补写金额          
				from T_C_SUM_OPER where fDate between @DataBDate and @DataEDate
				 and fAppID not in (select fPurseCode from T_B_PurseCode where fPurseType = 1)  
		            
				SET @AccountCount = @AccountCount + @khCount - @ChCount;          
				SET @AccountBalance = @AccountBalance + @KhMoney - @KhPndge + @SvMoney - @ChMoney - @GsPndge - @JgPndge - @TkMoney - 
				                      @ConsMoney + @JcMoney - @BkPndge - @BkMoney - @HkPndge + @SbMoney - @SbClrMoney;
				                      
				select @ConsMoneyJC = ISNULL(SUM(fMoney), 0) from T_C_SUM_Pos  
				 where fDate between @DataBDate and @DataEDate and fTType in (0, 17)        
				   and fPurseID 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),      --存款人数(计次)                
								@SvMoneyJC = 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),      --取款人数(计次)            
								@TkMoneyJC = 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),      --纠错人数(计次)           
								@JcMoneyJC = 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),      --补助人数(计次)             
								@SbMoneyJC = ISNULL(SUM( (case when fTType = 3 and fCType = 0 then fMoney else 0 end) ), 0),      --补助金额(计次)             
						              
								@SbClrCountJC =  ISNULL(SUM( (case when fTType = 37 and fCType = 0 then fCount else 0 end) ), 0), --补助清零人数 (计次)            
								@SbClrMoneyJC =  ISNULL(SUM( (case when fTType = 37 and fCType = 0 then fMoney else 0 end) ), 0)  --补助清零金额(计次) 
				from T_C_SUM_OPER where fDate between @DataBDate and @DataEDate  
				 and fAppID in (select fPurseCode from T_B_PurseCode where fPurseType = 1)     
		      
				set @AccountBalanceJC = @AccountBalanceJC - @ConsMoneyJC + @SvMoneyJC - @TkMoneyJC + @JcMoneyJC + @SbMoneyJC - @SbClrMoneyJC                  
											
				insert into T_R_SysAccount_Month(fDataYM, fDataBDate, fDataEDate, fConsCount, fConsMoney, fkhCount, fKhMoney, fKhDpsit, fKhPndge, 
				                                 fKhManage, fChCount, fChMoney, fChDpsit, fChPndge, fGsCount, fGsPndge, fJgCount, fJgPndge,
				                                 fSvCount, fSvPndge, fSvMoney, fTkCount, fTkMoney, fHkCount, fHkPndge, fBkCount, fBkMoney,
				                                 fBkPndge, fJcCount, fJcMoney, fSbCount, fSbMoney, fsbClrCount, fsbClrMoney, fQCCount, fQCMoney,
				                                 fQCBXCount, fQCBXMoney, fAccountCount, fAccountBalance, fConsMoneyJC, fSbCountJC, fSbMoneyJC, 
				                                 fSbClrCountJC, fSbClrMoneyJC, fJcCountJC, fJcMoneyJC, fSvCountJC, fSvMoneyJC, fTkCountJC, 
				                                 fTkMoneyJC, fAccountBalanceJC, fAccountDate)
    values(@TempDataYM, @DataBDate, @DataEDate, @ConsCount, @ConsMoney, @khCount, @KhMoney, @KhDpsit, @KhPndge,
           @KhManage, @ChCount, @ChMoney, @ChDpsit, @ChPndge, @GsCount, @GsPndge, @JgCount, @JgPndge,
           @SvCount, @SvPndge, @SvMoney, @TkCount, @TkMoney, @HkCount, @HkPndge, @BkCount, @BkMoney,
				       @BkPndge, @JcCount, @JcMoney, @SbCount, @SbMoney, @sbClrCount, @sbClrMoney, @QCCount, @QCMoney,
				       @QCBXCount, @QCBXMoney, @AccountCount, @AccountBalance, @ConsMoneyJC, @SbCountJC, @SbMoneyJC, 
				       @SbClrCountJC, @SbClrMoneyJC, @JcCountJC, @JcMoneyJC, @SvCountJC, @SvMoneyJC, @TkCountJC, 
				       @TkMoneyJC, @AccountBalanceJC, GETDATE())        

				set @TempDataYM = convert(varchar(7), DATEADD(mm, 1, (@TempDataYM + '-01 00:00:00')), 120) 
				set @SuccCount = @SuccCount + 1    
  end
  if @SuccCount > 0
     set @Ret = '1|结算成功'
  else
     set @Ret = '2|未到结算时间不能结算'   
END  
go

/*PROC_ADD_5 创建存储过程 - 生成人员月汇总表数据，由一卡通服务程序跨月时调用*/
create procedure [dbo].[UP_Make_Cns_SumEmpMonth]
  @Year  varchar(4), --年，'YYYY'   
  @Month varchar(2), --月，'MM' 
  @ReSumFlag bit,    --如果已有数据是否重新结算，0：不重新结算；1：重新结算
  @Ret varchar(50) output --状态值|原因
as      
begin 
  declare @AccountDay int         --月结算日期,0：自然月；其余为财务月日期
  declare @CurrDataYM varchar(7) --本次数据年月
  declare @SQL nvarchar(4000)      
  declare @iRet int      
  declare @sRet varchar(1200)
  declare @TbName varchar(30) 
  declare @DataBDate datetime
  declare @DataEDate datetime
   
  set @Ret = '0|未处理'
  set @AccountDay = 0
  select @AccountDay = fParamValue from T_B_SysParam where fParamName = 'SysMonthAccountDate' 
  
  if (@AccountDay < 0) or (@AccountDay > 28)  
  begin
    set @Ret = '0|设定财务结算日期非法'
    return
  end
  
  set @CurrDataYM = @Year + '-' + right('00'+ltrim(@Month),2)     
  set @DataBDate = @CurrDataYM + '-01 00:00:00'
           
  exec SP_Wst_CheckSumEmpMonthTable @DataBDate, @sRet output  
  
  if @sRet = ''
  begin
    set @Ret = '0|创建人员月结算表出错' 
    return
  end  
  
  set @TbName = @sRet
 
  set @SQL = ' Set @iRet = 0 
               if exists(select * from ' + @TbName + ')
               begin          
					if ' + CONVERT(varchar(3), @ReSumFlag) + ' = 1
					begin
						delete ' + @TbName + '
						delete from T_C_SumEmpDealByMonth where fDate=''' + @CurrDataYM + '''
					end
					else
					begin
							Set @iRet = 1  
					end          
				end '
															  
		exec sp_executesql @SQL, N'@iRet int output', @iRet output    
		--print @iRet
		if @iRet = 1
		begin
		  set @Ret = '0|当月结算数据已经存在，你选择了不重新结算'
		  return 
		end	
		
		if @AccountDay = 0 --自然月
		begin
				set @DataBDate = @CurrDataYM + '-01 00:00:00'
				set @DataEDate = DATEADD(mm, 1, @DataBDate)
				set @DataEDate = DATEADD(DD, -1, @DataEDate)
		end
		else
		begin
				if @AccountDay < 15
				begin
						set @DataBDate = @CurrDataYM + '-' + RIGHT('00' + convert(varchar(3), @AccountDay), 2) + ' 00:00:00'
						set @DataEDate = DATEADD(mm, 1, @DataBDate)
						set @DataEDate = DATEADD(DD, -1, @DataEDate)      
				end
				else
				begin
						set @DataEDate = @CurrDataYM + '-' + RIGHT('00' + convert(varchar(3), @AccountDay), 2) + ' 00:00:00'
						set @DataBDate = DATEADD(mm, -1, @DataEDate)
						set @DataBDate = DATEADD(dd, 1, @DataBDate)    
				end
		end
  
		if datediff(dd, @DataEDate, getdate()) < 1
		begin
				set @Ret = '0|到结算时间不能结算'
				return
		end	

  exec UP_R_CheckTime @DataBDate, @DataEDate, 5, @iRet output, @sRet output      
		--print @sRet      
		if @iRet = -9999 OR @sRet = '' 
		begin     
				set @Ret = '0|查询表无效-查询表范围超期'
				return
		end
     
  --将消费数据用一个视图保存下来  
  set @SQL = '
  if exists (select * from dbo.sysobjects where id = object_id(N''[dbo].[V_C_SumEmpTemp]'') and OBJECTPROPERTY(id, N''IsView'') = 1)      
     drop view [dbo].[V_C_SumEmpTemp] '
  EXEC(@SQL) 
     
  set @SQL = ' CREATE VIEW [dbo].[V_C_SumEmpTemp] 
               AS 
                 SELECT * FROM ' + @sRet  
  --PRINT @sRet   
  EXEC(@SQL) 
  
  if not exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[V_C_SumEmpTemp]') and OBJECTPROPERTY(id, N'IsView') = 1)
  begin
    set @Ret = '0|创建所需视图失败'
    return
  end
  
		CREATE TABLE #T_C_SumEmp(
				[fAccountID] [varchar](8) NOT NULL,				
				[fPurseID] [int] NOT NULL,
				[fOldBalance] [numeric](19, 2) NOT NULL DEFAULT (0),
				[fConsCount] [int] NOT NULL DEFAULT (0),
				[fConsMoney] [numeric](19, 2) NOT NULL DEFAULT (0),
				[fLimitConsCount] [int] NOT NULL DEFAULT (0),
				[fLimitConsMoney] [numeric](19, 2) NOT NULL DEFAULT (0),
				[fSaveCount] [int] NOT NULL DEFAULT (0),
				[fSaveMoney] [numeric](19, 2) NOT NULL DEFAULT (0),
				[fTakeCount] [int] NOT NULL DEFAULT (0),
				[fTakeMoney] [numeric](19, 2) NOT NULL DEFAULT (0),
				[fSubCount] [int] NOT NULL DEFAULT (0),
				[fSubMoney] [numeric](19, 2) NOT NULL DEFAULT (0),
				[fClearCount] [int] NOT NULL DEFAULT (0),
				[fClearMoney] [numeric](19, 2) NOT NULL DEFAULT (0),
				[fPutRightCount] [int] NOT NULL DEFAULT (0),
				[fPutRightMoney] [numeric](19, 2) NOT NULL DEFAULT (0),
				[fDiscountCount] [int] NOT NULL DEFAULT (0),
				[fDiscountMoney] [numeric](19, 2) NOT NULL DEFAULT (0),
				[fFee1] [numeric](19, 2) NOT NULL DEFAULT (0),
				[fFee2] [numeric](19, 2) NOT NULL DEFAULT (0),
				[fFee3] [numeric](19, 2) NOT NULL DEFAULT (0),
				[fFee4] [numeric](19, 2) NOT NULL DEFAULT (0),
				[fNewBalance] [numeric](19, 2) NOT NULL DEFAULT (0))  
   
   insert into #T_C_SumEmp(fAccountID, fPurseID,	fOldBalance)				                       
   select fAccountID, fPurseID, fOldBalance from V_C_SumEmpTemp 
           where fdate = @DataBDate
  
   --insert into #T_C_SumEmp(fAccountID, fPurseID,	fOldBalance)				                       
   --select fAccountID, fPurseID, fOldBalance from (
   --       select fAccountID, fPurseID, fOldBalance, ROW_NUMBER() over(ParTition by fAccountID, fPurseID order by fDate) fRn
   --         from V_C_SumEmpTemp 
   --        where fdate >= @DataBDate and fdate <= @DataEDate) R1
   -- where fRn = 1

   insert into #T_C_SumEmp(fAccountID, fPurseID,	fNewBalance)    
   select fAccountID, fPurseID, fNewBalance from V_C_SumEmpTemp 
    where fdate = @DataEDate
    
   --insert into #T_C_SumEmp(fAccountID, fPurseID,	fNewBalance)    
   --select fAccountID, fPurseID, fNewBalance from (
   --       select fAccountID, fPurseID,	fNewBalance, ROW_NUMBER() over(ParTition by fAccountID, fPurseID order by fDate desc) fRn
   --         from V_C_SumEmpTemp 
   --        where fdate >= @DataBDate and fdate <= @DataEDate) R1
   -- where fRn = 1    
    
   insert into #T_C_SumEmp(fAccountID, fPurseID,	fConsCount,	fConsMoney,	fLimitConsCount,	fLimitConsMoney,	fSaveCount,
			                       	fSaveMoney,	fTakeCount,	fTakeMoney, fSubCount,	fSubMoney,	fClearCount,	fClearMoney, fPutRightCount,
				                       fPutRightMoney,	fDiscountCount,	fDiscountMoney,	fFee1,	fFee2,	fFee3,	fFee4)        
    
   select fAccountID, fPurseID,  
          isnull(sum(fConsCount), 0), isnull(sum(fConsMoney), 0.00), isnull(sum(fLimitConsCount), 0), isnull(sum(fLimitConsMoney), 0.00), 
          isnull(sum(fSaveCount), 0), isnull(sum(fSaveMoney), 0.00), isnull(sum(fTakeCount), 0), isnull(sum(fTakeMoney), 0.00), 
          isnull(sum(fSubCount), 0), isnull(sum(fSubMoney), 0.00), isnull(sum(fClearCount), 0), isnull(sum(fClearMoney), 0.00), 
          isnull(sum(fPutRightCount), 0), isnull(sum(fPutRightMoney), 0.00), isnull(sum(fDiscountCount), 0), isnull(sum(fDiscountMoney), 0.00), 
          isnull(sum(fFee1), 0.00), isnull(sum(fFee2), 0.00), isnull(sum(fFee3), 0.00), isnull(sum(fFee4), 0.00)     
     from V_C_SumEmpTemp 
    where fdate >= @DataBDate and fdate <= @DataEDate 
    group by fAccountID, fPurseID 
   
   select fAccountID, fPurseID,	sum(fOldBalance) fOldBalance,	sum(fConsCount) fConsCount,	sum(fConsMoney) fConsMoney,	
          sum(fLimitConsCount) fLimitConsCount,	sum(fLimitConsMoney) fLimitConsMoney,	sum(fSaveCount) fSaveCount,
       			sum(fSaveMoney) fSaveMoney,	sum(fTakeCount) fTakeCount,	sum(fTakeMoney) fTakeMoney, sum(fSubCount) fSubCount,	
       			sum(fSubMoney) fSubMoney,	sum(fClearCount) fClearCount,	sum(fClearMoney) fClearMoney, sum(fPutRightCount) fPutRightCount,
										sum(fPutRightMoney) fPutRightMoney,	sum(fDiscountCount) fDiscountCount,	sum(fDiscountMoney) fDiscountMoney,	
										sum(fFee1) fFee1,	sum(fFee2) fFee2,	sum(fFee3) fFee3,	sum(fFee4) fFee4,	sum(fNewBalance) fNewBalance
					into #T_C_SumEmp1					
				 from #T_C_SumEmp                                         
    group by fAccountID, fPurseID
    
   drop table #T_C_SumEmp
   
   set @SQL = '
   insert into ' + @TbName + '(fKeyID,fDataYM,fAccountID,fPurseID,fOldBalance,fConsCount,fConsMoney,fLimitConsCount,fLimitConsMoney,
                               fSaveCount,fSaveMoney,fTakeCount,fTakeMoney,fSubCount,fSubMoney,fClearCount,fClearMoney,fPutRightCount,
                               fPutRightMoney,fDiscountCount,fDiscountMoney,fFee1,fFee2,fFee3,fFee4,fNewBalance,fAccountDate) 
   select REPLACE(''' + @CurrDataYM + ''', ''-'', '''') + fAccountID + CONVERT(varchar(3), fPurseID), ''' + @CurrDataYM + ''', 
          fAccountID, fPurseID,	fOldBalance,	fConsCount, fConsMoney,	fLimitConsCount,	fLimitConsMoney,	fSaveCount,	fSaveMoney,	
          fTakeCount,	fTakeMoney, fSubCount,	fSubMoney,	fClearCount,	fClearMoney, fPutRightCount, fPutRightMoney,	fDiscountCount,	
          fDiscountMoney,	fFee1,	fFee2,	fFee3,	fFee4,	fNewBalance, GETDATE() 
     from #T_C_SumEmp1'                                      
   --print @sql
   exec(@sql)
   
   drop table #T_C_SumEmp1
  set @Ret = '1|成功'
  if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[V_C_SumEmpTemp]') and OBJECTPROPERTY(id, N'IsView') = 1)      
     drop view [dbo].[V_C_SumEmpTemp]   
	 
  -- 记录数据      
  if exists(select  * from T_C_SumEmpDealByMonth   where fDate=@CurrDataYM)
     update T_C_SumEmpDealByMonth set fCreateTime=GETDATE(),fOpreID=99999 where fDate=@CurrDataYM
  else
     insert INTO T_C_SumEmpDealByMonth(fDate,fCreateTime,fOpreID)VALUES(@CurrDataYM,GETDATE(),99999)
end
go 

create procedure dbo.UP_InsertOnLineRecord_Step1 
   @PurseID INT,      --钱包编号        
   @FlowType INT,      --流水类型        
   @RecType INT,      --交易类型        
   @UserCardID VARCHAR(16),   --用户卡号(物理卡号/应用序列号)        
   @PosID INT,       --交易终端号        
   @CreateTime DATETIME,    --交易时间        
   @RecvTime DATETIME,     --入库时间        
   @Amount money ,    --交易额        
   @Discount money ,   --折扣额        
   @SourceID INT,      --来源        
   @TaskID INT,      --任务编号        
   @OperID INT,      --操作员编号         
   @Fee1 money ,    --其他费用1(手续费)        
   @Fee2 money ,    --其他费用2(卡费)        
   @Fee3 money ,    --其他费用3(押金)        
   @Fee4 money ,    --其他费用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 money ,  --交易前余额        
  @Balance money ,   --交易后余额        
  @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 
 ELSE IF @RecType IN (@WtTake, @WtDebitForLoad, @WtOut, @WtDel, @WtDelNOCard,@WtLoss,@WtUnLoss,@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 
 ELSE 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 
 ELSE 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


create procedure dbo.UP_InsertOnLineRecord_Step2 
   @PurseID INT,      --钱包编号        
   @FlowType INT,      --流水类型        
   @RecType INT,      --交易类型        
   @UserCardID VARCHAR(16),   --用户卡号(物理卡号/应用序列号)        
   @PosID INT,       --交易终端号        
   @CreateTime DATETIME,    --交易时间        
   @RecvTime DATETIME,     --入库时间  ，为步骤1的@SettleTime      
   @Amount money ,    --交易额        
   @Discount money ,   --折扣额        
   @SourceID INT,      --来源        
   @TaskID INT,      --任务编号        
   @OperID INT,      --操作员编号         
   @Fee1 money ,    --其他费用1(手续费)        
   @Fee2 money ,    --其他费用2(卡费)        
   @Fee3 money ,    --其他费用3(押金)        
   @Fee4 money ,    --其他费用4(管理费)        
   @OffTranNo INT,      --卡脱机交易序号        
   @PosTranNo INT,      --终端联机交易序号         
   @PosOffTranNo INT,     --终端脱机交易序号        
   @fRecKey VARCHAR(200),    --数据校验Key值    
   @fExternalOrder VARCHAR(100), 
   --以下是比step1多的参数，避免再次查询
   @OldMoney money ,  
   @Balance money ,   
   @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 money         
  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


create procedure dbo.UP_InsertOnLineRecord_Step3 
   @PurseID INT,      --钱包编号             
   @RecType INT,      --交易类型        
   @AccountID VARCHAR(16),--账号   
   @PosID INT,       --交易终端号        
   @MealID varchar(3),    --餐次        
   @RecvTime DATETIME,     --入库时间   为步骤1的@SettleTime 
   @OldMoney money , --原余额       
   @Amount money ,    --交易额 
   @Balance money ,    --现余额       
   @Discount money ,   --折扣额              
   @OperID INT,      --操作员编号         
   @Fee1 money ,    --其他费用1(手续费)        
   @Fee2 money ,    --其他费用2(卡费)        
   @Fee3 money ,    --其他费用3(押金)        
   @Fee4 money ,    --其他费用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


create procedure dbo.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 money 
             
  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


create procedure dbo.UP_MakeSysAccontByday 
  @Date nvarchar(10)     --格式：2018-08-08 
  as
begin    
  declare @OldAcount       bigint;           --原账户人数    
  declare @OldAcountMoney  money ;    --原账户金额     
  declare @OldAcountMoneyJC int;              --原账户金额(计次)        
  declare @ConsCount       bigint;           --营业人数    
  declare @ConsMoney       money ;    --营业金额     
  declare @ConsMoneyJC     int;              --营业金额(计次)          
  declare @khCount         int;              --开户人数    
  declare @KhtlSum         money ;    --开户金额    
  declare @KhDpsit         money ;    --开户押金       
  declare @KhPndge         money ;    --开户手续费    
  declare @KhManage        money ;    --开户管理费    
  declare @ChCount         int;              --撤户人数    
  declare @ChtlSum         money ;    --撤户金额     
  declare @ChMoney         money ;    --应退押金    
  declare @ChPndge         money ;    --撤户手续费     
  declare @GsCount         int;              --挂失人数     
  declare @GsPndge         money ;    --挂失手续费    
  declare @JgCount         int;              --解挂人数    
  declare @JgPndge         money ;    --解挂手续费    
  declare @SvCount         int;              --存款人数    
  declare @SvPndge         money ;    --存款管理费    
  declare @SvtlSum         money ;    --存款金额    
  declare @TkCount         int;              --取款人数    
  declare @TktlSum         money ;    --取款金额    
    
  declare @SvCountJC         int;              --存款人数(计次)     
  declare @SvtlSumJC         int;              --存款金额(计次)     
  declare @TkCountJC         int;              --取款人数(计次)     
  declare @TktlSumJC         int;              --取款金额(计次)   
   
  declare @HkCount         int;              --换卡人数    
  declare @HkPndge         money ;    --换卡手续费    
  declare @BkCount         int;              --补卡人数    
  declare @BktlSum         money ;    --补卡卡费     
  declare @BkPndge         money ;    --补卡手续费    
  declare @JcCount         int;              --纠错人数    
  declare @JctlSum         money ;    --纠错金额    
  declare @JcCountJC         int;            --纠错人数(计次)     
  declare @JctlSumJC         int;            --纠错金额(计次)     
  declare @SbCount         int;              --补助人数      
  declare @SbtlSum         money ;    --补助金额    
  declare @SbCountJC         int;            --补助人数(计次)       
  declare @SbtlSumJC         int;            --补助金额(计次)    
  declare @sbClearCount    int;              --补助清除人数    
  declare @sbClearSum      money ;    --补助清除金额    
  declare @sbClearCountJC    int;            --补助清除人数(计次)      
  declare @sbClearSumJC      int;            --补助清除金额(计次)     
  declare @QCCount         int;              --圈存人数    
  declare @QCtlSum         money ;    --圈存金额    
  declare @QCBXCount       int;              --圈存补款人数    
  declare @QCBXtlSum       money ;    --圈存补款金额    
  declare @NewAcount       bigint;           --现账户人数    
  declare @NewAcountMoney  money ;    --现账户金额     
  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  money  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  money  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  money  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  money  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


create procedure dbo.UP_ManualBackupDatabase 
    @DirName varchar(200),	--备份路径
  	@FileName varchar(50)	--备份文件名 
  	as
declare @DirExists bit
CREATE TABLE #tmp ([FileExists] BIT, [DirExists] BIT, [ParentDirExists] BIT)
INSERT INTO #tmp ([FileExists], [DirExists], [ParentDirExists]) 
EXEC master.dbo.xp_fileexist @DirName
select @DirExists=DirExists from #tmp
if @DirExists=0 begin
select -1 as ResultID, '路径不存在' as ResultMsg
RETURN
end

--得到当前数据库名
declare @DBName varchar(100)
/*
CREATE TABLE #TempTable (
	spid int,
	exid int,
	status varchar(50),
	loginame varchar(200),
	hostname varchar(200),
	blk int,
	dbname varchar(200),
    	cmd varchar(200)
)
insert #TempTable Exec sp_who @@spid
select @DBName=dbname from #TempTable
*/
set @DBName=db_name()

declare @BackupFile varchar(250)
set @BackupFile=@DirName+@FileName
backup database @DBName to disk=@BackupFile with init
update T_B_SysParam Set fParamValue=getdate(), fRestrict=1 where fParamName='LastFullBackupDate'
select 0 as ResultID, '备份成功' as ResultMsg
go


create procedure dbo.UP_REPORT_ATD_DAYS 
    @STATION  VARCHAR(20), 
  	@STRWHERE VARCHAR(1000),
  	@TIMEBEGIN VARCHAR(20),
  	@TIMEEND VARCHAR(20) 
  	as
DECLARE @STRSQL NVARCHAR(1000)
DECLARE @TMPWHERE NVARCHAR(500)
SET @TMPWHERE=''
IF (@STRWHERE<>'')
BEGIN 
	SET @TMPWHERE = '账号 IN (SELECT FACCOUNTID FROM T_B_EMPLOYEE WHERE '+@STRWHERE+') AND ' 
	END
SET @STRSQL='SELECT * FROM V_A_REPORTDAY
WHERE  '+@TMPWHERE+'
考勤日期>='''+@TIMEBEGIN+''' AND 考勤日期<='''+@TIMEEND+''''
EXEC SP_EXECUTESQL @STRSQL
go


create procedure dbo.UP_REPORT_ATD_MONTHS 
    @STATION  VARCHAR(20), 
  	@STRWHERE VARCHAR(1000),
  	@YEAR INT,
  	@MONTHS VARCHAR(100) 
  	as
DECLARE @STRSQL NVARCHAR(1000)
DECLARE @TMPWHERE NVARCHAR(500)
SET @TMPWHERE=''
IF (@STRWHERE<>'')
BEGIN 
	SET @TMPWHERE = '账号 IN (SELECT FACCOUNTID FROM T_B_EMPLOYEE WHERE '+@STRWHERE+') AND ' 
	END
SET @STRSQL='SELECT * FROM V_A_REPORTMONTH
WHERE  '+@TMPWHERE+'
年份='+CAST(@YEAR AS VARCHAR(4))+' AND 月份 IN (0'+@MONTHS+')'
EXEC SP_EXECUTESQL @STRSQL
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


create procedure dbo.UP_RecordBAWListDown 
    @fPosID int,           --0表示所有 >0表示对应的机号
  	@fListType varchar(2), --0:CB消费黑名单 1:CW消费白名单 2:AW考勤白名单 3:EW门禁白名单 CL:Clear清空（机器初始化后得第一条指令）
  	@fVer int              --版本号 
  	as
BEGIN
	if @fListType not in ('CB','AW','EW','CL') Return
	if @fListType = 'CL' --清除下载的数据
	begin
	  --将需要删除的流水转移至备份表
	  INSERT INTO T_B_ListDownHis (fID, fType, fPosID, fVer, fTime, fDesc)
		SELECT fID, fType, fPosID, fVer, fTime, fDesc		
		FROM T_B_ListDown WHERE fPosID = @fPosID 
	  --删除表中符合的数据
	  DELETE FROM T_B_ListDown WHERE fPosID = @fPosID
      UPDATE T_B_Pos SET fWVer = 0, fBVer = 0 
        WHERE fPosID = @fPosID
	end
	else
	begin
		Declare @fID int
		SET @fID = -1
		SELECT @fID = fID FROM T_B_ListDown
		 WHERE fPosID = @fPosID AND
			   fVer   = @fVeR AND
			   fType  = @fListType 
		IF @fID = -1
			INSERT INTO T_B_ListDown
				   (fType, fPosID, fVer, fTime, fDesc)
			 VALUES	
				   (@fListType,@fPosID,@fVer,GETDATE(),'')
		ELSE
			UPDATE T_B_ListDown
			   SET fTime  = GETDATE()
			 WHERE fID  = @fID
	end
END
go


create procedure dbo.UP_Report_Atd_Arranging 
    @year varchar(4),
  	@month varchar(4),
  	@strWhere varchar(2000) 
  	as
declare @SQLStr nvarchar(4000)
	if @strWhere<>''
	begin set @strWhere=@strWhere+' and' end
	begin
	set @SQLStr='select a.fAccountID as 账号,d.fCardNo as 卡号,a.fname as 姓名,
				c.fDeptName as 部门,a.fyear as 年,a.fmonth as 月,
				case when fDay1=b.fWorkTimeCode then b.fWorkTimeName else '''' end as ''1号'',
				case when fDay2=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''2号'',
				case when fDay3=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''3号'',
				case when fDay4=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''4号'',
				case when fDay5=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''5号'',
				case when fDay6=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''6号'',
				case when fDay7=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''7号'',
				case when fDay8=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''8号'',
				case when fDay9=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''9号'',
				case when fDay10=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''10号'',
				case when fDay11=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''11号'',
				case when fDay12=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''12号'',
				case when fDay13=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''13号'',
				case when fDay14=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''14号'',
				case when fDay15=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''15号'',
				case when fDay16=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''16号'',
				case when fDay17=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''17号'',
				case when fDay18=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''18号'',
				case when fDay19=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''19号'',
				case when fDay20=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''20号'',
				case when fDay21=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''21号'',
				case when fDay22=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''22号'',
				case when fDay23=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''23号'',
				case when fDay24=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''24号'',
				case when fDay25=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''25号'',
				case when fDay26=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''26号'',
				case when fDay27=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''27号'',
				case when fDay28=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''28号'',
				case when fDay29=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''29号'',
				case when fDay30=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''30号'',
				case when fDay31=b.fWorkTimeCode  then b.fWorkTimeName else '''' end as ''31号'' 
				from T_A_WTArrange a,T_A_WorkTime b,dbo.T_B_Dept c,dbo.T_B_Employee d 
				where '+@strWhere+' a.fyear='+@Year+' and a.fmonth='+@month+' 
				and a.fDay1=b.fWorkTimeCode and a.fAccountID=d.fAccountID and d.fDept=c.fDeptCode'
	end
	exec sp_executesql @SQLStr
go


create procedure dbo.UP_Report_Atd_CardRecord 
    @strWhere varchar(1000),
  	@RecType int,
  	@BeginDate datetime,
  	@EndDate datetime,
  	@PosID varchar(5)='' 
  	as
BEGIN
declare @b_Year varchar(4)
	declare @b_Month varchar(2)

	DECLARE @STRSQL nvarchar(4000),
	        @iRet int,
	        @sRet varchar(300)
	        
	EXEC UP_R_CheckTime @BeginDate, @EndDate, 2, @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 @b_Year=datename(yyyy,@BeginDate)
	set @b_Month=datename(mm,@BeginDate)

	set @BeginDate=Cast(@BeginDate as varchar(10))+' 00:00:00'
	set @EndDate=Cast(@EndDate as varchar(10))+' 23:59:59'

	declare @i int
	declare @MonthCount int
	declare @sql_table nvarchar(4000)
	declare @CurrDate datetime
	set @i=0
	set @MonthCount=datediff(mm,@BeginDate,@EndDate)

	declare @tmpWhere varchar(500)
	DECLARE @PosWhere nvarchar(100)
	declare @sType varchar(200)
	set @sType=''
	if @RecType<>0 
		set @sType= 'fRecordedType='+cast(@RecType as varchar(2))+' and '


	declare @TableName varchar(21)
	set @sql_table=''
	while (@i<=@MonthCount)
	begin
		set @CurrDate=dateadd(m,@i,@BeginDate)
		set @TableName='T_A_CardRecord_'+datename(yyyy,@CurrDate)+dbo.fn_FillZero(2,datename(mm,@CurrDate))

		set @tmpWhere=''
		if (@strWhere<>'')
		begin 
			set @tmpWhere = +@TableName+'.fAccountID in (SELECT fAccountID FROM T_B_Employee WHERE '+@StrWhere+') and ' 
		end

		SET @PosWhere=''
		IF (@PosID<>0)
		BEGIN 
			SET @PosWhere = 'and '+@TableName+'.fPosID = '+@PosID 
		END

		if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].['+@TableName+']') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
		begin
			if @sql_table<>'' set @sql_table=@sql_table+CHAR(10)+' UNION '+CHAR(10)
			set @sql_table=@sql_table+' SELECT '+@TableName+'.[fKeyID] as 序号,T_B_Employee.fName as 姓名, '+@TableName+'.[fAccountID] as 账号,  
			T_B_Employee.fEmployeeCode as 工号, '+@TableName+'.[fCardNo] as 卡号, T_B_Dept.fDeptName as 部门, [fRecordedTime] as 打卡时间, [fReceiveTime] as 收取时间, 
			dbo.FN_CastAtdRecType([fRecordedType]) as 打卡类型, T_B_Pos.fPosName as 打卡设备,TM.fLoginName AS 操作员
			FROM '+@TableName+' INNER JOIN T_B_Employee ON 
				'+@TableName+'.fAccountID = T_B_Employee.fAccountID LEFT OUTER JOIN T_B_Pos ON '+@TableName+'.fPosID=T_B_Pos.fPosID 
			LEFT OUTER JOIN T_B_Dept ON T_B_Employee.fDept = T_B_Dept.fDeptCode
			LEFT OUTER JOIN T_B_Manager TM ON '+@TableName+'.FOPERID=TM.fOperID
			
			
			
			WHERE '+@sType+@tmpWhere+'(fRecordedTime>='''+convert(varchar(19),@begindate,20)+''' and fRecordedTime<='''+convert(varchar(19),@enddate,20)+''') ' + @PosWhere
		end
		set @i=@i+1
	end
	exec sp_executesql @sql_Table
END
go


create procedure dbo.UP_Report_Atd_CardRecordN 
   @STATION  VARCHAR(20),   
   @STRWHERE VARCHAR(1000),  
   @RECTYPE INT,  
   @BEGINDATE DATETIME,  
   @ENDDATE DATETIME,  
   @POSID VARCHAR(5)='' 
   as
BEGIN  
 DECLARE @STRSQL nvarchar(4000),  
         @iRet int,  
         @sRet varchar(300)  
           
 EXEC UP_R_CheckTime @BeginDate, @EndDate, 2, @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  
 DECLARE @B_YEAR VARCHAR(4)  
 DECLARE @B_MONTH VARCHAR(2)  
 SET @B_YEAR=DATENAME(YYYY,@BEGINDATE)  
 SET @B_MONTH=DATENAME(MM,@BEGINDATE)  
 SET @BEGINDATE=CAST(@BEGINDATE AS VARCHAR(10))+' 00:00:00'  
 SET @ENDDATE=CAST(@ENDDATE AS VARCHAR(10))+' 23:59:59'  
 DECLARE @I INT  
 DECLARE @MONTHCOUNT INT  
 DECLARE @SQL_TABLE NVARCHAR(4000)  
 DECLARE @CURRDATE DATETIME  
 SET @I=0  
 SET @MONTHCOUNT=DATEDIFF(MM,@BEGINDATE,@ENDDATE)  
 DECLARE @TMPWHERE VARCHAR(500)  
 DECLARE @POSWHERE NVARCHAR(100)  
 DECLARE @STYPE VARCHAR(200)  
 declare @PicTableName varchar(40)  
  
 SET @STYPE=''  
 IF @RECTYPE<>0   
  SET @STYPE= 'FRECORDEDTYPE='+CAST(@RECTYPE AS VARCHAR(2))+' AND '  
 DECLARE @TABLENAME VARCHAR(21)  
 SET @SQL_TABLE=''  
 WHILE (@I<=@MONTHCOUNT)  
 BEGIN  
  SET @CURRDATE=DATEADD(M,@I,@BEGINDATE)  
  SET @TABLENAME='T_A_CARDRECORD_'+DATENAME(YYYY,@CURRDATE)+DBO.FN_FILLZERO(2,DATENAME(MM,@CURRDATE))  
  set @PicTableName='T_A_CardRecordPic_'+datename(yyyy,@CurrDate)+dbo.fn_FillZero(2,datename(mm,@CurrDate))  
  SET @TMPWHERE=''  
  IF (@STRWHERE<>'')  
  BEGIN   
   SET @TMPWHERE = +@TABLENAME+'.FACCOUNTID IN (SELECT FACCOUNTID FROM T_B_EMPLOYEE WHERE '+@STRWHERE+') AND '   
  END  
  SET @POSWHERE=''  
  IF (@POSID<>0)  
  BEGIN   
   SET @POSWHERE = 'AND '+@TABLENAME+'.FPOSID = '+@POSID   
  END  
  IF EXISTS (SELECT * FROM DBO.SYSOBJECTS WHERE ID = OBJECT_ID(N'[DBO].['+@TABLENAME+']') AND OBJECTPROPERTY(ID, N'ISUSERTABLE') = 1)  
  begin  
   if @sql_table<>'' set @sql_table=@sql_table+CHAR(10)+' UNION ALL '+CHAR(10)  
   set @sql_table=@sql_table+' SELECT '+@TableName+'.[fKeyID] as 序号,T_B_Employee.fName as 姓名, '+@TableName+'.[fAccountID] as 账号,    
   T_B_Employee.fEmployeeCode as 工号, '+@TableName+'.[fCardNo] as 卡号, T_B_Dept.fDeptName as 部门, ' + @TableName + '.[fRecordedTime] as 打卡时间, [fReceiveTime] as 收取时间,   
   dbo.FN_CastAtdRecType([fRecordedType]) as 打卡类型, T_B_Pos.fPosName as 打卡设备, ' + @PicTableName + '.fRecPic as 图片  
   FROM '+@TableName+' LEFT JOIN T_B_Employee ON   
    '+@TableName+'.fAccountID = T_B_Employee.fAccountID LEFT OUTER JOIN T_B_Pos ON '+@TableName+'.fPosID=T_B_Pos.fPosID   
   LEFT OUTER JOIN T_B_Dept ON T_B_Employee.fDept = T_B_Dept.fDeptCode  
   LEFT OUTER JOIN ' + @PicTableName + ' ON ' + @TableName + '.fKeyID = ' + @PicTableName + '.fKeyID  
   WHERE '+@sType+@tmpWhere+'(' + @TableName + '.fRecordedTime>='''+convert(varchar(19),@begindate,20)+''' and ' + @TableName + '.fRecordedTime<='''+convert(varchar(19),@enddate,20)+''') ' + @PosWhere  
  end  
  SET @I=@I+1  
 END  
 EXEC SP_EXECUTESQL @SQL_TABLE  
 PRINT @SQL_TABLE  
END
go


create procedure dbo.UP_Report_Atd_EmpByMonth 
        @Station varchar(8),
 	    @strWhere varchar(1000),
 	    @Year  varchar(10),
        @Month varchar(10) 
        as
begin
--*/
/*
    declare    @Station varchar(8)=''
	declare    @strWhere varchar(1000)=''
	declare    @Year  varchar(10)='2012'
    declare    @Month varchar(10)='06'
*/

 declare @Where  varchar(2000)
 declare @WYear  varchar(10),
         @WMonth varchar(10),
         @days varchar(10) ,
         @Sel varchar(2000)   --最终查询字段

  declare @sqlstr varchar(8000)
  set @sqlstr = ''
  
  declare @CheckDate varchar(20)
  declare @sdate datetime   --查询开始时间
  declare @edate datetime   --查询结束时间
  Set @WYear = @Year
  if Len(@Month)= 1 
    Set @WMonth = '0' + @Month
  else
    Set @WMonth =  @Month  
  Set @sdate = @WYear + '-' + @WMonth + '-01 00:00:00' 
  set @days = 32-Day(@sdate+(32-Day(@sdate)))
  Set @edate = @WYear + '-' + @WMonth + '-' + @days + ' 23:59:59' 
  

  
  --循环得取每天对应的SQL查询
  declare  curChkDate cursor for
  
  select convert(char(10),DATEADD(dd,number,@sdate),120) as date from master..spt_values 
   where type = 'P' and DATEADD(dd,number,@sdate) < DATEADD(mm,1,@sdate);  

  open curChkDate
  fetch next  from curChkDate into  @CheckDate
  
  Set @Sel = ' select E.fEmployeeCode as 工号,E.fname as 姓名,F.fDeptName as 部门,h.fDiplomaName AS 班次,G.fNationName as 小组'   
  select @sqlstr = @sqlstr + char(13) + '(select t.fAccountID '


  while @@fetch_status = 0
  begin
    --select @sqlstr = @sqlstr +',case when t.fDt  = ''' + @CheckDate+ ''' then t.fMk end as [' + datename(dd,@CheckDate)+']'  +char(13)
    select @sqlstr = @sqlstr +',isnull(max(case when t.fDt  = ''' + @CheckDate+ ''' then t.fMk end),'' '') as [' + datename(dd,@CheckDate)+']'  +char(13)
    Set @Sel = @Sel + ', A.[' + datename(dd,@CheckDate) + ']'                       
   fetch next from curChkDate into @CheckDate
 end 
 deallocate  curChkDate
 
  Set @Sel = @Sel + ',c.kg as [旷工] '
 
 --循环得取班次对应的SQL查询
  declare @WTCode varchar(20)
  declare  curWorkTime cursor for
  select fWorkTimeCode from T_A_WorkTime
  open curWorkTime
  fetch next  from curWorkTime into  @WTCode
  
  while @@fetch_status = 0
  begin
    select @sqlstr = @sqlstr +',sum(isnull(case when t.fWorkTimeCode=''' + @WTCode+ ''' then t.fIsHave end,0)) as [' + fWorkTimeName +']'  ,
           @Sel = @Sel + ', A.[' + fWorkTimeName + '] as [' + SUBSTRING(fWorkTimeName,1,1) + '] '
       from T_A_WorkTime 
       where fWorkTimeCode = @WTCode
    fetch next from curWorkTime into @WTCode
  end 
  deallocate  curWorkTime 
  
  
 if @strWhere <> '' 
   set @Where = ' where ' + @strWhere
 else
   set @Where =  ''
 Set @Sel = @Sel + ',A.[加],A.[饭] '
 
 select @sqlstr = @sqlstr + char(13) +
       ',sum(isnull(fOvertimeCount,0)) as [加] ' +
       ','''' as [饭] from( '+
	   'select R1.fAccountID '+
			',convert(char(10),R1.fCheckDate,120) as fDt '+
			',R1.fWorkTimeCode '+
			',case when (R1.fOvertimeMinutes <> 0) then  1 else 0 end [fOvertimeCount] '+   --加班
			',case when (R1.fOnDuty1 <> '''') then 1 '+
				  'else 0 end as fIsHave '+                                              --当班是否有效
			',case when CHARINDEX(''全天未打卡'',R1.fExplain)>0 then ''旷'' '+ 
			      'when (R1.fOverdueCount = 1) or (R1.fOverdueMinutes <> 0) then  ''迟'' '+ 
			      'when (R1.fEarlyCount = 1) or (R1.fEarlyMinutes <> 0) then  ''退'' '+
			      'when (R1.fLeaveDays = 1) or (R1.fLeaveMinutes <> 0) then substring(L.fLeaveName,1,1) '+ -- ''请假'' 
			      'when (R1.fEvectionDays <> 0) or (R1.fEvectionMinutes <> 0) then ''差'' '+
			      'when CHARINDEX(''休息'',R1.fExplain)>0 then '' '' '+ 
			      'when CHARINDEX(''缺打卡'',R1.fExplain)>0 then ''缺'' '+ 
			      'when (R1.fOnDuty1 <> '''') then substring(Wt.fWorkTimeName,1,1) '+
			      'when (R1.fOvertimeMinutes <> 0) then ''加'' '+
			      'else '''' end as [fMk] '+ --当班的状态
	  'from '+ 
	  '(select * from [T_A_ReportDays] '+ 
        'where fCheckDate>=''' + CONVERT(varchar(100), @sdate, 25) 
               + ''' and fCheckDate <= '''+ CONVERT(varchar(100), @edate, 25) 
               +''') R1 left join T_A_WorkTime Wt on R1.fWorkTimeCode = Wt.fWorkTimeCode '+
		       'left join  (select fAccountID,fLeaveType,CONVERT(varchar(10), fTimeBegin, 20) as sDate  FROM [T_B_LeaveReclist] T1 '+
			  'WHERE fTimeBegin >= ''' + CONVERT(varchar(100), @sdate, 25) + '''  and fTimeBegin < ''' + CONVERT(varchar(100), @edate, 25) + ''' '+
			                                                                                     ----                                                                                                        ---------
					'and not exists(select * from T_B_LeaveReclist where fAccountID=T1.fAccountID  and CONVERT(varchar(10),fTimeBegin, 20) = CONVERT(varchar(10),T1.fTimeBegin, 20) and fTimeBegin<T1.fTimeBegin)  '+
			  ') Lr on convert(char(10),R1.fCheckDate,120) = Lr.sDate and R1.fAccountID = Lr.fAccountID '+
			  'Left join T_B_Leave L on Lr.fLeaveType = L.fLeaveCode ) as t ' + char(13) +
               ' group by  t.fAccountID ) A'
--print @sqlstr              

  select @sqlstr = @sqlstr + ' left join (select fAccountID '

 --循环得取班次对应的SQL查询
  declare @LeaveCode varchar(20)
  declare  curLeave cursor for
  select fLeaveCode from T_B_Leave   
  open curLeave
  fetch next  from curLeave into  @LeaveCode
  
  while @@fetch_status = 0
  begin
    select @sqlstr = @sqlstr +',sum(case when fLeaveType = ''' + @LeaveCode+ ''' then iCount else 0 end) as [' + fLeaveName+']'  ,
           @Sel = @Sel + ',CAST(isnull(B.[' + fLeaveName + '],0) as varchar(20)) as [' + substring(fLeaveName,1,1) + ']'
       from T_B_Leave 
       where fLeaveCode = @LeaveCode
    fetch next from curLeave into @LeaveCode
  end 
  deallocate  curLeave 

set @sqlstr = @sqlstr + char(13) +
' from(select fAccountID, fLeaveType,sum(CEILING(CONVERT(float,ftimeEnd,23)-CONVERT(float,fTimeBegin,23))) as iCount '+
' FROM [T_B_LeaveReclist]where fTimeBegin>=''' + CONVERT(varchar(100), @sdate, 25)+ ''' and fTimeBegin<'''+ CONVERT(varchar(100), @edate, 25)+''' '+
' group by fAccountID,fLeaveType) t group by fAccountID) B on A.fAccountID=B.fAccountID '  
	   
--print @sqlstr  	

Set @Sel = @Sel + CHAR(13) +
          ' from '
Set @sqlstr = @Sel + @sqlstr + CHAR(13)  +
--  增加旷工列的汇总
' INNER JOIN (select fAccountID, count(kg) as [KG] from(select fAccountID,case when CHARINDEX(''全天未打卡'',fExplain)>0 then ''旷''  end as kg from [T_A_ReportDays] '+
' where fCheckDate>=''' + CONVERT(varchar(100), @sdate, 25)+ '''  and fCheckDate<'''+ CONVERT(varchar(100), @edate, 25)+''''+
' ) as k group by fAccountID) C ON A.fAccountID = C.fAccountID '+             -----


             ' INNER JOIN (select fAccountID, fEmployeeCode ,fname,fDept,fNation,fDiploma from T_B_Employee ' + @Where + ')E on A.fAccountID=E.fAccountID ' + 
             ' Left JOIN (select fDeptCode,fDeptName from T_B_Dept) F on E.fDept=F.fDeptCode ' +
             ' Left JOIN (select fNationCode,fNationName from T_B_Nation) G on E.fNation=G.fNationCode '+
             ' Left JOIN (select fDiplomaCode,fDiplomaName from T_B_Diploma) H on E.fDiploma=H.fDiplomaCode '+
             ' order by fDept,fNation,fDiploma'
             

----------print @sqlstr
exec(@sqlstr)

end
go

/*REPORT_ADD_5 创建存储过程 - 查询 - 系统总表*/
create PROCEDURE [dbo].[UP_Report_Cns_SysAccont_Month]
  @StationID char(2), --工作站点
  @Year  varchar(4),  --年，'YYYY'   
  @Month varchar(2)   --月，'MM'
AS          
BEGIN 
  declare @CurrDataYM varchar(7)     --本次数据年月
  declare @LastDataYM varchar(7)     --上次数据年月
  declare @MinDataYM varchar(7)      --最早数据年月
  declare @LastAccountCount int      --原账户人数
  declare @LastAccountBalance money  --原账户余额
  declare @LastAccountBalanceJC int  --原账户计次余额
  
  declare @AccountCount     bigint = 0;   --现账户人数
  declare @AccountBalance   Money = 0.00; --现账户余额
  declare @ConsCount        bigint = 0;   --消费次数       
  declare @ConsMoney        Money = 0.00; --消费金额         
  declare @khCount          int;          --开户次数
  declare @KhMoney          Money = 0.00; --开户金额         
  declare @KhDpsit          Money = 0.00; --开户押金         
  declare @KhPndge          Money = 0.00; --开户手续费         
  declare @KhManage         Money = 0.00; --开户管理费         
  declare @ChCount          int = 0;      --撤户次数    
  declare @ChMoney          Money = 0.00; --撤户金额         
  declare @ChDpsit          Money = 0.00; --撤户押金         
  declare @ChPndge          Money = 0.00; --撤户手续费         
  declare @GsCount          int = 0;      --挂失次数    
  declare @GsPndge          Money = 0.00; --挂失手续费         
  declare @JgCount          int = 0;      --解挂次数    
  declare @JgPndge          Money = 0.00; --解挂手续费         
  declare @SvCount          int = 0;      --存款次数    
  declare @SvMoney          Money = 0.00; --存款金额         
  declare @SvPndge          Money = 0.00; --存款手续费         
  declare @TkCount          int = 0;      --取款次数    
  declare @TkMoney          Money = 0.00; --取款金额         
  declare @HkCount          int = 0;      --换卡次数    
  declare @HkPndge          Money = 0.00; --换卡手续费         
  declare @BkCount          int = 0;      --补卡次数    
  declare @BkMoney          Money = 0.00; --补卡金额         
  declare @BkPndge          Money = 0.00; --补卡手续费         
  declare @JcCount          int = 0;      --纠错次数    
  declare @JcMoney          Money = 0.00; --纠错金额         
  declare @SbCount          int = 0;      --补助次数    
  declare @SbMoney          Money = 0.00; --补助金额         
  declare @sbClrCount       int = 0;      --补助清零次数    
  declare @sbClrMoney       Money = 0.00; --补助清零金额
  declare @QCCount          int = 0;      --圈存次数    
  declare @QCMoney          Money = 0.00; --圈存金额         
  declare @QCBXCount        int = 0;      --圈存补写次数    
  declare @QCBXMoney        Money = 0.00; --圈存补写金额         
  
  declare @AccountCountJC   int = 0;      --现账户人数
  declare @AccountBalanceJC int = 0;      --原账户金额(计次)
  declare @ConsMoneyJC      int = 0;      --营业金额(计次)
  declare @SvCountJC        int = 0;      --存款人数(计次)       
  declare @SvMoneyJC        int = 0;      --存款金额(计次)       
  declare @TkCountJC        int = 0;      --取款人数(计次)       
  declare @TkMoneyJC        int = 0;      --取款金额(计次) 
  declare @JcCountJC        int = 0;      --纠错人数(计次)       
  declare @JcMoneyJC        int = 0;      --纠错金额(计次)
  declare @SbCountJC        int = 0;      --补助人数(计次)         
  declare @SbMoneyJC        int = 0;      --补助金额(计次) 
  declare @sbClrCountJC     int = 0;      --补助清除人数(计次)        
  declare @sbClrMoneyJC     int = 0;      --补助清除金额(计次) 
  
  set @CurrDataYM = @Year + '-' + @Month 
  set @LastDataYM = convert(varchar(7), dateadd(mm, -1, @CurrDataYM + '-01 00:00:00'), 120)
  select top 1 @MinDataYM = CONVERT(varchar(7), fdate, 120) from T_C_SUM_OPER
   order by fDate
   
  if not exists(select * from T_R_SysAccount_Month where fDataYM = @CurrDataYM)
  begin
    select '系统尚无当月结算数据，请先结算' as 提示
    return
  end 
  
  if @CurrDataYM <> @MinDataYM
  begin
    if not exists(select * from T_R_SysAccount_Month where fDataYM = @LastDataYM)
    begin
      select '系统无上月结算数据，无法得出期初余额，请保持结算数据月份连续！' as 提示
      return    
    end
  end
  
  set @LastAccountCount = 0       
  set @LastAccountBalance = 0.00
  set @LastAccountBalanceJC = 0
    
  select @LastAccountCount = fAccountCount, @LastAccountBalance = fAccountBalance, @LastAccountBalanceJC = fAccountBalanceJC 
    from T_R_SysAccount_Month 
   where fDataYM = @LastDataYM
   
  select @AccountCount = fAccountCount, @AccountBalance = fAccountBalance, @ConsCount = fConsCount, @ConsMoney = fConsMoney,         
         @khCount = fkhCount, @KhMoney = fKhMoney, @KhDpsit = fKhDpsit, @KhPndge = fKhPndge, @KhManage = fKhManage,    
         @ChCount = fChCount, @ChMoney = fChMoney, @ChDpsit = fChDpsit, @ChPndge = fChPndge, @GsCount = fGsCount, 
         @GsPndge = fGsPndge, @JgCount = fJgCount, @JgPndge = fJgPndge, @SvCount = fSvCount, @SvMoney = fSvMoney, 
         @SvPndge = fSvPndge, @TkCount = fTkCount, @TkMoney = fTkMoney, @HkCount = fHkCount, @HkPndge = fHkPndge, 
         @BkCount = fBkCount, @BkMoney = fBkMoney, @BkPndge = fBkPndge, @JcCount = fJcCount, @JcMoney = fJcMoney,  
         @SbCount = fSbCount, @SbMoney = fSbMoney, @sbClrCount = fsbClrCount, @sbClrMoney = fsbClrMoney, 
         @QCCount = fQCCount, @QCMoney = fQCMoney, @QCBXCount  = fQCBXCount, @QCBXMoney = fQCBXMoney, 
         @AccountBalanceJC = fAccountBalanceJC, @ConsMoneyJC = fConsMoneyJC, @SvCountJC = fSvCountJC,
         @SvMoneyJC = fSvMoneyJC, @TkCountJC = fTkCountJC, @TkMoneyJC = fTkMoneyJC, @JcCountJC = fJcCountJC,
         @JcMoneyJC = fJcMoneyJC, @SbCountJC = fSbCountJC, @SbMoneyJC = fSbMoneyJC, @sbClrCountJC = fSbClrCountJC,
         @sbClrMoneyJC = fSbClrMoneyJC  
    from T_R_SysAccount_Month 
   where fDataYM = @CurrDataYM
  if @@ROWCOUNT = 0
  begin
    set @AccountCount = @LastAccountCount 
    set @AccountBalance = @LastAccountBalance
    set @AccountBalanceJC = @LastAccountBalanceJC
  end 
  
  create table #Tmp_SysAccount(              
				Item1      varchar(64),              
				Item1Count int,              
				Item2      varchar(64),              
				Item2Value money,              
				Item3      varchar(64),              
				Item3Value money,        
				Item4      varchar(64),              
				Item4Value int)  
				
		insert into #Tmp_SysAccount(Item1, Item1Count, Item2, Item2Value, Item3, Item3Value, Item4, Item4Value)    
		values('原账户人数', @LastAccountCount, '原账户余额', @LastAccountBalance, null, null, '原账户余额(计次)', @LastAccountBalanceJC) 
		
		insert into #Tmp_SysAccount(Item1, Item1Count, Item2, Item2Value, Item3, Item3Value, Item4, Item4Value)      
	values('开户人数', @khCount, '开户金额', @KhMoney, '开户押金', @KhDpsit, null, null)
		        
		insert into #Tmp_SysAccount(Item1, Item1Count, Item2, Item2Value, Item3, Item3Value, Item4, Item4Value)      
		values(null, null, '开户卡费', @KhPndge, '开户管理费', @KhManage, null, null)
		    
		insert into #Tmp_SysAccount(Item1, Item1Count, Item2, Item2Value, Item3, Item3Value, Item4, Item4Value)      
	values('撤户人数', @ChCount, '撤户余额', @ChMoney, '撤户手续费', @ChPndge, '充值人次(计次)', @SvCountJC)
		          
		insert into #Tmp_SysAccount(Item1, Item1Count, Item2, Item2Value, Item3, Item3Value, Item4, Item4Value)      
		values(null, null, '应退押金', @ChDpsit, '退款金额', (@ChMoney - @ChPndge + @ChDpsit), '充值金额(计次)', @SvMoneyJC)
		
		insert into #Tmp_SysAccount(Item1, Item1Count, Item2, Item2Value, Item3, Item3Value, Item4, Item4Value)      
		values('营业人次', @ConsCount, '营业金额', @ConsMoney, null, null, '营业金额(计次)', @ConsMoneyJC)		
		    
		insert into #Tmp_SysAccount(Item1, Item1Count, Item2, Item2Value, Item3, Item3Value, Item4, Item4Value)      
		values('存款人数', @SvCount, '存款金额', @SvMoney, '存款管理费', @SvPndge, '取款人次(计次)', @TkCountJC)
			
		insert into #Tmp_SysAccount(Item1, Item1Count, Item2, Item2Value, Item3, Item3Value, Item4, Item4Value)      
		values('取款人数', @TkCount, '取款金额', @TkMoney, null, null, '取款金额(计次)', @TkMoneyJC)
			
		insert into #Tmp_SysAccount(Item1, Item1Count, Item2, Item2Value, Item3, Item3Value, Item4, Item4Value)      
		values('挂失人数', @GsCount, '挂失手续费', @GsPndge, null, null, '纠错人数(计次)', @JcCountJC)
			
		insert into #Tmp_SysAccount(Item1, Item1Count, Item2, Item2Value, Item3, Item3Value, Item4, Item4Value)      
		values('解挂人数', @JgCount, '解挂手续费', @JgPndge, null, null, '纠错金额(计次)', @JcMoneyJC)
			
		insert into #Tmp_SysAccount(Item1, Item1Count, Item2, Item2Value, Item3, Item3Value, Item4, Item4Value)      
		values('换卡人数', @HkCount, '换卡手续费', @HkPndge, null, null, '补助人数(计次)', @SbCountJC)
			
		insert into #Tmp_SysAccount(Item1, Item1Count, Item2, Item2Value, Item3, Item3Value, Item4, Item4Value)      
		values('补卡人数', @BkCount, '补卡卡费', @BkMoney, '补卡手续费', @BkPndge, '补助金额(计次)', @SbMoneyJC)
			
		insert into #Tmp_SysAccount(Item1, Item1Count, Item2, Item2Value, Item3, Item3Value, Item4, Item4Value)      
		values('纠错人数', @JcCount, '纠错金额', @JcMoney, null, null, '补助清零人数(计次)', @SbClrCountJC)
			     
		insert into #Tmp_SysAccount(Item1, Item1Count, Item2, Item2Value, Item3, Item3Value, Item4, Item4Value)      
		values('补助人数', @SbCount, '补助金额', @SbMoney, null, null, '补助清零金额(计次)', @SbClrMoneyJC)
			
		insert into #Tmp_SysAccount(Item1, Item1Count, Item2, Item2Value, Item3, Item3Value, Item4, Item4Value)      
		values('补助清零人数', @SbClrCount, '补助清零金额', @SbClrMoney, null, null, null, null)
			
		insert into #Tmp_SysAccount(Item1, Item1Count, Item2, Item2Value, Item3, Item3Value, Item4, Item4Value)      
		values('圈存人数', @QCCount, '圈存金额', @QCMoney, null, null, null, null)
			            
		insert into #Tmp_SysAccount(Item1, Item1Count, Item2, Item2Value, Item3, Item3Value, Item4, Item4Value)      
		values('圈存补款人数', @QCBXCount, '圈存补款金额', @QCBXMoney, null, null, null, null)
			
		insert into #Tmp_SysAccount(Item1, Item1Count, Item2, Item2Value, Item3, Item3Value, Item4, Item4Value)      
		values('现账户人数', @AccountCount, '现账户余额', @AccountBalance, null, null, '现账户余额(计次)', @AccountBalanceJC)
		                
		select Item1 [项目1], Item1Count [项目1数量], Item2 [项目2], Item2Value [项目2金额] ,        
									Item3 [项目3], Item3Value [项目3金额], Item4 [项目4], Item4Value [项目4金额]           
				from #Tmp_SysAccount 
END 
go 


CREATE procedure [dbo].[UP_Report_Cns_AccountBalance_M] 
  @STATIONID varchar(2), --工作站  
  @Year  varchar(4),     --年，'YYYY'     
  @Month varchar(2),     --月，'MM'  
  @PurseID varchar(200)  --钱包编号，0：查询所有钱包        
as        
begin     
  declare @TbName varchar(25)  
  declare @Where varchar(100)  
  declare @Sql nvarchar(4000)  
    
  set @TbName = 'T_C_SumEmpMonth_' + @Year + @Month  
    
  if not exists(select * from dbo.sysobjects where id = OBJECT_ID(@TbName) and objectproperty(id, N'IsTable') = 1)   
  begin  
    select @Year + '年' + @Month + '月数据尚未结算，请先进行结算' as 提示  
    return  
  end  
    
  set @Where = ''  
    
  if @PurseID <> ''  
     set @Where = ' where ' + @PurseID  
       
  set @Sql =   
    ' select E.fName [姓名], R.fAccountID [账号], E.fDept [部门编码], D.fDeptName [部门名称], R.fPurseID [钱包编号],  
         P.fPurseName [钱包名称], R.fOldBalance [期初余额], R.fConsCount [消费|次数], R.fConsMoney [消费|金额],   
         R.fSaveCount [存款|次数], R.fSaveMoney [存款|金额], R.fTakeCount [取款|次数], R.fTakeMoney [取款|金额],  
         R.fSubCount [补助|次数], R.fSubMoney [补助|金额], R.fClearCount [补助清除|次数], R.fClearMoney [补助清除|金额],  
         R.fPutRightCount [纠错|次数], R.fPutRightMoney [纠错|金额], R.fDiscountCount [优惠|次数], R.fDiscountMoney [优惠|金额],  
         R.fFee1 [手续费],R.fFee2 [卡费],R.fFee3 [押金],R.fFee4 [管理费],R.fNewBalance [期末余额]     
  from ' + @TbName + ' R left join T_B_Employee E on R.fAccountID = E.fAccountID  
       left join T_B_Dept D on E.fDept = D.fDeptCode  
       left join T_B_PurseCode P on R.fPurseID = P.fPurseCode ' + CHAR(13) + @Where     
  print @Sql  
  exec(@Sql)  
end
go 

create procedure dbo.UP_Report_Bas_ActDetail 
  @strWhere varchar(1000) 
as
DECLARE @strsql nvarchar(1000)
IF @strWhere<>'' set @strWhere='WHERE '+@strWhere

SET @strsql='SELECT dbo.T_B_Employee.fName AS 姓名, 
      dbo.T_B_Employee.fAccountID AS 账号, 
      dbo.T_B_Employee.fEmployeeCode AS 学工号,
       dbo.T_B_Employee.fCardNo AS 卡号, 
      dbo.T_B_Dept.fDeptName AS 部门, 
      CASE WHEN dbo.T_B_Employee.fSex=0 THEN ''女'' ELSE ''男'' END AS 性别, 
      dbo.T_B_ManType.fId_TypeName AS 身份类型, 
      CASE WHEN dbo.T_B_Employee.fCard_State=0 THEN ''正常'' 
	   WHEN dbo.T_B_Employee.fCard_State=1 THEN ''挂失''
	   WHEN dbo.T_B_Employee.fCard_State=2 THEN ''销卡'' 
	   WHEN dbo.T_B_Employee.fCard_State=3 THEN ''未发卡''
	   WHEN dbo.T_B_Employee.fCard_State=4 THEN ''撤户'' END AS 卡状态, 
      dbo.T_B_Employee.fL_Money AS 余额, 
      dbo.T_B_Employee.fPhysicalNo AS 卡物理号
FROM dbo.T_B_Employee LEFT OUTER JOIN
      dbo.T_B_ManType ON 
      dbo.T_B_Employee.fId_TypeId = dbo.T_B_ManType.fId_TypeId LEFT OUTER JOIN
      dbo.T_B_Dept ON dbo.T_B_Employee.fDept = dbo.T_B_Dept.fDeptCode '+@strWhere
--print @strsql
exec sp_executesql @strsql
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

create procedure dbo.UP_Report_Cns_CLByOper 
    @StationID varchar(2),
  	@BeginDate datetime,
  	@EndDate datetime 
  	as
set @BeginDate=Cast(@BeginDate as varchar(10))+' 00:00:00'
set @EndDate=Cast(@EndDate as varchar(10))+' 23:59:59'

if @StationID=''
	SELECT [工作站], [操作员], SUM([开户人数]) as [开户人数], SUM([开户金额]) as 开户金额, SUM([开户押金]) as 开户押金, SUM([开户卡费]) as 开户卡费, 
	SUM([开户管理费]) as 开户管理费, (SUM([开户金额])+SUM([开户押金])+SUM([开户卡费])) as 开户总金额,
	(Select sum(fkh_je) from T_B_Employee, T_B_OperateRec where T_B_Employee.fAccountID=T_B_OperateRec.fAccount_Id and T_B_Employee.fCard_State=3 and T_B_OperateRec.fOper_ID=a.操作员ID and fCons_Time>=@BeginDate and fCons_Time<=@EndDate and fCons_State='6') as 未发卡用户总金额,
	SUM([撤户人数]) as 撤户人数, SUM([撤户金额]) as 撤户金额, SUM([撤户押金]) 撤户押金, 
	SUM([撤户手续费]) as 撤户手续费, SUM([挂失人数]) as 挂失人数, SUM([挂失手续费]) as 挂失手续费, SUM([解挂人数]) as 解挂人数, 
	SUM([解挂手续费]) as 解挂手续费, SUM([存款人数]) as 存款人数, SUM([存款手续费]) as 存款手续费, SUM([存款金额]) as 存款金额, 
	SUM([取款人数]) as 取款人数, SUM([取款金额]) as 取款金额, SUM([换卡人数]) as 换卡人数, SUM([换卡手续费]) as 换卡手续费, 
	SUM([补卡人数]) as 补卡人数, SUM([补卡卡费]) as 补卡卡费, SUM([补卡手续费]) as 补卡手续费, SUM([纠错人数]) as 纠错人数, 
	SUM([纠错金额]) as 纠错金额, SUM([补助人数]) as 补助人数, SUM([补助金额]) as 补助金额 
	FROM [dbo].[V_B_OperAccount] a
	WHERE [出纳日期]>=@BeginDate and [出纳日期]<= @EndDate 
	GROUP BY [工作站], [操作员], [操作员ID]
ELSE
	SELECT [工作站], [操作员], SUM([开户人数]) as [开户人数], SUM([开户金额]) as 开户金额, SUM([开户押金]) as 开户押金, SUM([开户卡费]) as 开户卡费, 
	SUM([开户管理费]) as 开户管理费, (SUM([开户金额])+SUM([开户押金])+SUM([开户卡费])) as 开户总金额,
	(Select sum(fkh_je) from T_B_Employee, T_B_OperateRec where T_B_Employee.fAccountID=T_B_OperateRec.fAccount_Id and T_B_Employee.fCard_State=3 and T_B_OperateRec.fOper_ID=a.操作员ID and fCons_Time>=@BeginDate and fCons_Time<=@EndDate and fCons_State='6') as 未发卡用户总金额,
	SUM([撤户人数]) as 撤户人数, SUM([撤户金额]) as 撤户金额, SUM([撤户押金]) 撤户押金, 
	SUM([撤户手续费]) as 撤户手续费, SUM([挂失人数]) as 挂失人数, SUM([挂失手续费]) as 挂失手续费, SUM([解挂人数]) as 解挂人数, 
	SUM([解挂手续费]) as 解挂手续费, SUM([存款人数]) as 存款人数, SUM([存款手续费]) as 存款手续费, SUM([存款金额]) as 存款金额, 
	SUM([取款人数]) as 取款人数, SUM([取款金额]) as 取款金额, SUM([换卡人数]) as 换卡人数, SUM([换卡手续费]) as 换卡手续费, 
	SUM([补卡人数]) as 补卡人数, SUM([补卡卡费]) as 补卡卡费, SUM([补卡手续费]) as 补卡手续费, SUM([纠错人数]) as 纠错人数, 
	SUM([纠错金额]) as 纠错金额, SUM([补助人数]) as 补助人数, SUM([补助金额]) as 补助金额 
	FROM [dbo].[V_B_OperAccount] a
	WHERE [工作站号]=@StationID and ([出纳日期]>=@BeginDate and [出纳日期]<= @EndDate)
	GROUP BY [工作站], [操作员], [操作员ID]
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 money) AS 消费金额,           
   CAST(SUM(R.[消费|次]) AS INT) AS 消费次数,           
   CAST(SUM(R.[纠错|金额]) AS money) AS 纠错金额,           
   CAST(SUM(R.[纠错|次]) AS INT) AS 纠错次数,          
   --CAST(SUM(R.[计次|次]) AS INT) AS 计次次数,             
   CAST(SUM(R.[消费|金额] - R.[纠错|金额]) AS money) - CAST(SUM(ROUND((A.FTC_BL / 100)           
     * (R.[消费|金额] - R.[纠错|金额]), 2)) AS money) 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


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 money ) AS 消费金额,         
   CAST(SUM(R.[消费|次]) AS INT) AS 消费次数,         
   CAST(SUM(R.[纠错|金额]) AS money ) AS 纠错金额,         
   CAST(SUM(R.[纠错|次]) AS INT) AS 纠错次数,         
   --CAST(SUM(R.[计次|次]) AS INT) AS 计次次数,         
   CAST(SUM(R.[消费|金额] - R.[纠错|金额]) AS money ) - CAST(SUM(ROUND((A.FTC_BL / 100)         
     * (R.[消费|金额] - R.[纠错|金额]), 2)) AS money ) 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


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 money ) AS 消费金额,         
   CAST(SUM(R.[消费|次]) AS INT) AS 消费次数,         
   CAST(SUM(R.[纠错|金额]) AS money ) AS 纠错金额,         
   CAST(SUM(R.[纠错|次]) AS INT) AS 纠错次数,         
  -- CAST(SUM(R.[计次|次]) AS INT) AS 计次次数,         
   CAST(SUM(R.[消费|金额] - R.[纠错|金额]) AS money ) - CAST(SUM(ROUND((A.FTC_BL / 100)         
     * (R.[消费|金额] - R.[纠错|金额]), 2)) AS money ) 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


create procedure dbo.UP_Report_Cns_DeptCollect 
    @DeptID varchar(18),
  	@BeginDate datetime,
  	@EndDate datetime 
  	as
declare @SQL nvarchar(3000)
declare @DeptStr nvarchar(30)

set @BeginDate=Cast(@BeginDate as varchar(10))+' 00:00:00'
set @EndDate=Cast(@EndDate as varchar(10))+' 23:59:59'
if @DeptID='' 
	SET @DeptStr= ''
ELSE
	SET @DeptStr= 'and fDp_Bh='''+@DeptID+''' '

set @SQL=
'SELECT T_B_Dept.fDeptName as 部门, T_B_Employee.fName as 姓名,T_B_Employee.fEmployeeCode as 学工号,
Sum(消费次数) as 消费次数, Sum(总消费额) as 总消费额, Sum(取款次数) as 取款次数, Sum(总取款额) as 总取款额, 
Sum(存款次数) as 存款次数, sum(总存款额) as 总存款额, Sum(纠错次数) as 纠错次数, Sum(纠错总额) as 纠错总额, 
Sum(补助次数) as 补助次数, Sum(补助总额) as 补助总额, T_B_Employee.fL_Money as 现余额
FROM 
(SELECT fAccount_ID, Count(*) as 消费次数, Sum(fCons_Fare) as 总消费额, 0 as 取款次数, 0 as 总取款额, 0 as 存款次数, 0 as 总存款额, 0 as 纠错次数, 0 as 纠错总额, 0 as 补助次数, 0 as 补助总额
FROM T_C_ConsumerRec
WHERE (fCons_Time>='''+convert(varchar(19),@begindate,20)+''' and fCons_Time<='''+convert(varchar(19),@Enddate,20)+''') '+@DeptStr+'
GROUP BY fAccount_ID
UNION
SELECT  fAccount_ID, 0 as 消费次数, 0 as 总消费额, Count(*) as 取款次数, Sum(fCons_Fare) as 总取款额, 0 as 存款次数, 0 as 总存款额, 0 as 纠错次数, 0 as 纠错总额, 0 as 补助次数, 0 as 补助总额
FROM T_B_OperateRec
WHERE fCons_State=2 '+@DeptStr+' and (fCons_Time>='''+convert(varchar(19),@begindate,20)+''' and fCons_Time<='''+convert(varchar(19),@Enddate,20)+''') 
GROUP BY fAccount_ID
UNION
SELECT fAccount_ID, 0 as 消费次数, 0 as 总消费额, 0 as 取款次数, 0 as 总取款额, Count(*) as 存款次数, Sum(fCons_Fare) as 总存款额, 0 as 纠错次数, 0 as 纠错总额, 0 as 补助次数, 0 as 补助总额
FROM T_B_OperateRec 
WHERE fCons_State=1 '+@DeptStr+' and (fCons_Time>='''+convert(varchar(19),@begindate,20)+''' and fCons_Time<='''+convert(varchar(19),@Enddate,20)+''') 
GROUP BY fAccount_ID
UNION
SELECT fAccount_ID, 0 as 消费次数, 0 as 总消费额, 0 as 取款次数, 0 as 总取款额, 0 as 存款次数, 0 as 总存款额, Count(*) as 纠错次数, Sum(fCons_Fare) as 纠错总额, 0 as 补助次数, 0 as 补助总额
FROM T_B_OperateRec 
WHERE fCons_State=8 '+@DeptStr+' and (fCons_Time>='''+convert(varchar(19),@begindate,20)+''' and fCons_Time<='''+convert(varchar(19),@Enddate,20)+''') 
GROUP BY fAccount_ID
UNION
SELECT fAccount_ID,0 as 消费次数, 0 as 总消费额, 0 as 取款次数, 0 as 总取款额, 0 as 存款次数, 0 as 总存款额, 0 as 纠错次数, 0 as 纠错总额, Count(*) as 补助次数, Sum(fCons_Fare) as 补助总额
FROM T_B_OperateRec 
WHERE fCons_State=3 '+@DeptStr+' and (fCons_Time>='''+convert(varchar(19),@begindate,20)+''' and fCons_Time<='''+convert(varchar(19),@Enddate,20)+''') 
GROUP BY fAccount_ID ) A 
INNER JOIN
      T_B_Employee ON 
      A.fAccount_id = T_B_Employee.fAccountID LEFT OUTER JOIN
      T_B_Dept ON T_B_Employee.fDept = T_B_Dept.fDeptCode
GROUP BY T_B_Employee.fEmployeeCode, T_B_Dept.fDeptName,  T_B_Employee.fName, T_B_Employee.fL_Money'

--print @SQL
exec sp_executesql @SQL
go


create procedure dbo.UP_Report_Cns_Detail_DeptMeal 
       @StationID   varchar(20),       -- 工作站；  
       @BegDateTime varchar(20),       -- 开始查询日期  
       @EndDateTime varchar(20),       -- 结束查询日  
       @Dp_bh varchar(4096)='ALL',      -- 部门编号,不传入该参数将是所有部门
       @TotalOrDetail varchar(1),     --汇总还是明细 0-明细，1-汇总
       @PurseSum    varchar(1)     --钱包是否汇总统计 0- 否 1- 是 
       as
BEGIN  
 declare @VirtualAccountID varchar(40)  
 set @VirtualAccountID='00000000'  
 declare @STRSQL varchar(8000),  
   @iRet int,  
   @sRet varchar(300),  
   @strB varchar(30),  
   @strE varchar(30),  
   @strDP varchar(3000),
   @FieldStr1 varchar(1024),
   @FieldStr2 varchar(1024),
   @FieldStr3 varchar(1024),
   @FieldStr4 varchar(1024)
    
 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(@Dp_bh <> 'ALL') and (@Dp_bh <> '')   
    set @strDP = ' AND ' + @Dp_bh + ' ' + CHAR(13)  
  else  
    set @strDP = '' 
  set @FieldStr1=''  
  set @FieldStr2=''  
  set @FieldStr3=''
  SET @FieldStr4=''
    
  if  @PurseSum='0' 
  begin
    set @FieldStr1=' a.fPurseCode as 钱包编码 ,a.fPurseName as 钱包名称, '   
    SET @FieldStr2=' ,C.fPurseCode,C.fPurseName ' 
    SET @FieldStr3=' ,a.fPurseCode,a.fPurseName '  
    SET @FieldStr4='  钱包名称,'  
  end
  
  if @TotalOrDetail='0' 
  begin
     SET @STRSQL =  
	  'select  账号,姓名,[消费|次数],[消费|金额],[存款|次数], [存款|金额],[取款|次数],[取款|金额],'+@FieldStr4+'[签字]
	   FROM (select a.fAccountID as 账号,max(b.fName) 姓名 , sum(consCount) as [消费|次数],  
	  sum(consfare) as [消费|金额],sum(svcount) as [存款|次数],sum(svmoney) as [存款|金额],  
	  sum(tkcount) as [取款|次数],sum(tkmoney) as [取款|金额],'+@FieldStr1+'   
	  '' '' as [签字]   
	  from   
	  (  
	  select R.fAccountID,Sum(case when R.fRecType in(0,17) then 1 when R.fRecType=8 then -1 else 0 end) as consCount,  
			sum(case when R.fRecType in(0,17) then R.fAmount  when R.fRecType=8 then -R.fAmount else 0.00 end) as consfare, 
			Sum(case when R.fRecType in(1,28) then 1 else 0 end) as svcount,  
			sum(case when R.fRecType in(1,28) then R.fAmount else 0.00 end) as svmoney,  
			Sum(case when R.fRecType in(2,30) then 1 else 0 end) as tkcount,  
			sum(case when R.fRecType in(2,30) then R.fAmount else 0.00 end) as tkmoney '+@FieldStr2+' 
	  from '+CHAR(13)+  
	  @sRet +CHAR(13)+  
	   ' LEFT JOIN T_B_PurseCode C ON R.fPurseID=C.fPurseCode'+
	   ' where R.fSettleTime >= ''' + @strB + ''' AND R.fSettleTime <= ''' +@strE + ''' AND   
		 R.fAccountID <> '''+@VirtualAccountID + ''' and R.fRecType in(0,1,2,8,17,28,30) ' + CHAR(13) +  
	  @strDP +   
	  'group by R.fAccountID '+@FieldStr2+'    
	  ) as a inner join T_B_Employee b on a.fAccountID = b.fAccountID  and b.fcard_state not in (3,4)  
	   group by a.fAccountID '+@FieldStr3 +' ) t order by  账号'
   
  end
  else
  begin
	 SET @STRSQL =  
		  'select  编号,名称,[消费|次数],[消费|金额],[存款|次数], [存款|金额],[取款|次数],[取款|金额],'+@FieldStr4+'[签字]
		   from (select a.fDeptCode as 编号,max(b.fDeptName) 名称 , sum(consCount) as [消费|次数],  
		  sum(consfare) as [消费|金额],sum(svcount) as [存款|次数],sum(svmoney) as [存款|金额],  
		  sum(tkcount) as [取款|次数],sum(tkmoney) as [取款|金额],'+@FieldStr1+'    
		  '' '' as [签字]   
		  from   
		  (  
		  select R.fDeptCode'+@FieldStr2+', 
		        
				Sum(case when R.fRecType in(0,17) then 1 when R.fRecType=8 then -1 else 0 end) as consCount,  
				sum(case when R.fRecType in(0,17) then R.fAmount  when R.fRecType=8 then -R.fAmount else 0.00 end) as consfare,  
				Sum(case when R.fRecType in(1,28) then 1 else 0 end) as svcount,  
				sum(case when R.fRecType in(1,28) then R.fAmount else 0.00 end) as svmoney,  
				Sum(case when R.fRecType in(2,30) then 1 else 0 end) as tkcount,  
				sum(case when R.fRecType in(2,30) then R.fAmount else 0.00 end) as tkmoney
		  from ' +CHAR(13)+  
		  @sRet +CHAR(13)+  
		  ' LEFT JOIN T_B_PurseCode C ON R.fPurseID=C.fPurseCode'+
		  '  inner join T_B_Employee d on r.fAccountID = d.fAccountID and d.fcard_state not in (3,4) '+
		   ' where R.fSettleTime >= ''' + @strB + ''' AND R.fSettleTime <= ''' +@strE + ''' AND R.fAccountID <> '''+@VirtualAccountID + ''' 
		   and R.fRecType in(0,1,2,8,17,28,30) '+ @strDP +' group by R.fDeptCode'+@FieldStr2+ '     
		  ) as a left join T_B_Dept b on a.fDeptCode = b.fDeptCode
		   group by a.fDeptCode'+@FieldStr3+') t'
  end
  print @STRSQL  
  exec(@STRSQL) 
 end  
 
  
END
go


create procedure dbo.UP_Report_Cns_Detail_Individual 
       @Station     varchar(20),  -- 工作站；传值，工作站名称，只能传入一个工作站名称
       @BegDateTime varchar(20),  --开始查询日期
       @AccountID   varchar(20)   --帐号 
       as
BEGIN
DECLARE @SQL nvarchar(4000),
		@strB varchar(30),
		@BTime datetime,
		@ETime datetime,
        @iRet int,
        @sRet varchar(300)		

SET @strB = CONVERT(varchar(20), @BegDateTime, 23) + ' 00:00:00'
SET @BTime = @BegDateTime
SET @ETime = GETDATE()

EXEC UP_R_CheckTime @BTime, @ETime, 1, @iRet output, @sRet output
if @iRet = -9999 OR @sRet = ''
  begin
    SET @SQL = 'SELECT ''查询表无效-查询表范围超期'' AS [返回信息]'
  end
  ELSE
  begin
    SET @SQL =
	'DECLARE @NewMoney money,
			@OldMoney money
	--获得期末余额
	select @NewMoney = isnull(fBalanceMon + fBalanceSub,0.00) from T_B_Employee where fAccountID = ''' + @AccountID + '''

	--期中
	SELECT identity(int,1,1) fKeyID, * 
	into #temp1
	from 
	(
	select R.fStation_id, S.fStation_Name, P.fSt_Id, P.fSt_Name, R.fPos_id as fpos, P.fPosName, 
		   R.fAccount_id,R.fCard_Number,E.fName, D.fDeptName,R.fCons_Time, 
		   C.fStateName as fCons_StateName,  R.fCons_State,
		   case when R.fCons_State in (1,3,33,38) then R.fCons_Fare
					when R.fCons_State=6 then R.fCons_Fare + R.fx_money + R.fSx_money
					--when R.fCons_State=7 then R.FManageMoney
					when R.fCons_State=8 then -R.fCons_Fare
					when R.fCons_State=28 then R.fCons_Fare
					--when R.fCons_State=37 then R.FCons_Fare
					else 0.00 end as sr,
		   case when R.fCons_State in(0,2,17,30,34) then R.fCons_Fare
					when R.fCons_State in (4,5,6,9) then R.fCons_Fare + R.fSx_money
					when R.fCons_State in (10) then R.fSx_money + R.FManageMoney
					when R.fCons_State in (7,25) then R.fOdd_Money --- R.fSx_money + R.FManageMoney
					when R.fCons_State in(1,6,28) then R.FManageMoney
					when R.fCons_State =37 then R.FCons_Fare
					else 0.00 end as zc,
		   cast(0.00 as money ) as jy,
		   case when fCons_State = 6 then ''支出含押金('' + CAST(R.fCons_Fare as varchar(20)) + '')''
				when fCons_State in(7,25) then ''另退押金('' + CAST(R.FManageMoney as varchar(20))+ '')''
				else  ''''
		   end as Remark,
		   R.fFKTIME
	from '  + CHAR(13) +
	@sRet + CHAR(13) +
   'Left join T_C_ConsState C on R.fCons_State = C.fStateID
	left join V_B_SitePos P on R.fPos_id = P.fPosID
	left join T_B_Station S on R.fStation_Id = S.fStation_Id
	left join T_B_Employee E on R.fAccount_id = E.fAccountID
	left join T_B_Dept D on R.fDp_bh = D.fDeptCode
	where R.fAccount_ID = ''' + @AccountID + ''' AND R.fCons_Time >= ''' + @strB + '''
	) as a
	order by fAccount_ID,fCons_Time,fFKTIME,fCons_State

	--期末
	declare @fKeyID int
	declare @sr money 
	declare @zc money 
	declare @Sumsr money 
	declare @Sumzc money 
	set @Sumsr = 0.00  --期末收入（输入之和）
	set @Sumzc = 0.00  --期末支出（支出之和）
	set @OldMoney = @NewMoney --期初余额
	
	DECLARE curMeal CURSOR FOR 
	select fKeyID, sr,zc from #temp1 order by fKeyID desc
	OPEN curMeal
	FETCH NEXT FROM curMeal INTO @fKeyID, @sr, @zc
	WHILE @@FETCH_STATUS = 0
	BEGIN
	   update #temp1 set jy = @OldMoney  where fKeyID = @fKeyID 	
	   set @OldMoney = @OldMoney - @sr + @zc
	   set @Sumsr = @Sumsr + @sr
	   set @Sumzc = @Sumzc + @zc
	   FETCH NEXT FROM curMeal INTO @fKeyID, @sr, @zc
	END
	select 
		'''' as fCons_Time, '''' as fStation_Name, '''' as fSt_Name, '''' as fPosName, '''' as fName, '''' as fCard_Number, '''' as fDeptName,
		''期末信息'' as fCons_StateName,cast(isnull(@Sumsr,0.00) as money ) as sr, 
		cast(isnull(@Sumzc,0.00) as money ) as zc, cast(isnull(@NewMoney,0.00) as money ) as jy,
		'''' as Remark
	into #temp3
	close curMeal
	DEALLOCATE curMeal

	select fCons_Time as 时间, fStation_Name as 工作站, fSt_Name as 营业组, fPosName as 机号, fName as 姓名, 
		   fCard_Number as 卡号, fDeptName as 部门, fCons_StateName as 摘要, sr as 收入, zc as 支出, jy as 结余, Remark as 备注 
	from 
	(
	 select '''' as fCons_Time, '''' as fStation_Name, '''' as fSt_Name, '''' as fPosName, '''' as fName, '''' as fCard_Number, '''' as fDeptName, ''期初信息'' as fCons_StateName, 0.00 as sr, 0.00 as zc, @OldMoney as jy, '''' as Remark 
	 union all
	 select  CONVERT(varchar(100), fCons_Time, 20), fStation_Name, fSt_Name, fPosName, fName, fCard_Number, fDeptName, fCons_StateName, sr, zc, jy, Remark 
	 from #temp1
	 union all
	 select fCons_Time, fStation_Name, fSt_Name, fPosName, fName, fCard_Number, fDeptName, fCons_StateName, sr, zc, jy, Remark 
	 from #temp3
	) as a
	drop table #temp1
	drop table #temp3 '
  end
 --print @SQL
 exec(@SQL)
END
go


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


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


create procedure dbo.UP_Report_Cns_OpenActRec 
    @strWhere varchar(1000),
  	@BeginDate datetime,
  	@EndDate datetime 
  	as
DECLARE @strB varchar(19)
DECLARE @strE varchar(19)
SET @strB=datename(yyyy, @BeginDate)+'-'+datename(mm, @BeginDate)+'-'+datename(dd, @BeginDate)+' '+'00:00:00'
SET @strE=datename(yyyy, @EndDate)+'-'+datename(mm, @EndDate)+'-'+datename(dd, @EndDate)+' '+'23:59:59'


DECLARE @strsql nvarchar(1000)
DECLARE @TmpWhere nvarchar(500)
DECLARE @ConsWhere nvarchar(100)
SET @TmpWhere=''
IF (@strWhere<>'')
BEGIN 
	SET @TmpWhere = '账号 IN (SELECT FAccountID FROM T_B_Employee WHERE '+@strWhere+') and ' 
END


SET @strsql='SELECT 姓名, 工号, 账号, 卡号, 部门, 发生时间 as 开户时间, 开户押金, 手续费 as 开户卡费, 现余额, 操作员
	FROM dbo.V_B_OperatorRec
	Where '+@TmpWhere+' 消费类型编码=6 and (发生时间>='''+@strB+''' and 发生时间<='''+@strE+''') '
--print @strsql
exec sp_executesql @strsql
go


create procedure dbo.proc_paged_2part_selectMax ( 
  	@tblName nvarchar(400),              ----要显示的表或多个表的连接 
  	@fldName nvarchar(500) = '*',        ----要显示的字段列表 
  	@pageSize int = 10,                  ----每页显示的记录个数 
  	@page int = 1,                       ----要显示那一页的记录 
  	@fldSort nvarchar(200) = null,       ----排序字段列表或条件 
  	@Sort bit = 1,                       ----排序方法，0为升序，1为降序(如果是多字段排列Sort指代最后一个排序字段的排列顺序(最后一个排序字段不加排序标记)--程序传参如：' SortA Asc,SortB Desc,SortC ') 
  	@strCondition nvarchar(1000) = null, ----查询条件,不需where 和 and
  	@ID nvarchar(150),                   ----主表的主键 
  	@Dist bit = 0,                       ----是否添加查询字段的 DISTINCT 默认0不添加/1添加 
  	@pageCount int = 1 output,           ----返回查询结果分页后的总页数 
  	@Counts int = 1 output,              ----返回查询到的记录数 
  	@SQLOUT nvarchar(2000) output        ----返回的查询语句
  ) as
SET NOCOUNT ON 
	Declare @sqlTmp nvarchar(2000) ----存放动态生成的SQL语句 
	Declare @strTmp nvarchar(2000) ----存放取得查询结果总数的查询语句 
	Declare @strID nvarchar(2000) ----存放取得查询开头或结尾ID的查询语句 

	Declare @strSortType nvarchar(10) ----数据排序规则A 
	Declare @strFSortType nvarchar(10) ----数据排序规则B 

	Declare @SqlSelect nvarchar(50) ----对含有DISTINCT的查询进行SQL构造 
	Declare @SqlCounts nvarchar(50) ----对含有DISTINCT的总数查询进行SQL构造 

	declare @timediff datetime --耗时测试时间差 
	select @timediff=getdate() 

	if @Dist = 0 
	begin 
	  set @SqlSelect = 'select ' 
	  set @SqlCounts = 'Count(*)' 
	end 
	else 
	begin 
	 set @SqlSelect = 'select distinct ' 
	 set @SqlCounts = 'Count(DISTINCT '+@ID+')' 
	end 


	if @Sort=0 
	begin 
	 set @strFSortType=' ASC ' 
	 set @strSortType=' DESC ' 
	end 
	else 
	begin 
	 set @strFSortType=' DESC ' 
	 set @strSortType=' ASC ' 
	end 

	--------生成查询语句-------- 
	--此处@strTmp为取得查询结果数量的语句 
	if @strCondition is null or @strCondition='' --没有设置显示条件 
	begin 
	 set @sqlTmp = @fldName + ' From ' + @tblName 
	 set @strTmp = @SqlSelect+' @Counts='+@SqlCounts+' FROM '+@tblName 
	 set @strID = ' From ' + @tblName 
	end 
	else 
	begin 
	 set @sqlTmp = + @fldName + ' From ' + @tblName + ' where ' + @strCondition 
	 set @strTmp = @SqlSelect+' @Counts='+@SqlCounts+' FROM '+ @tblName + ' where ' + @strCondition 
	 set @strID = ' From ' + @tblName + ' where ' + @strCondition 
	end 

	----取得查询结果总数量----- 
	--print @sqlTmp
	--print @strTmp
	--print @strID
	exec sp_executesql @strTmp,N'@Counts int out ',@Counts out 
	declare @tmpCounts int 
	if @Counts = 0 
	 set @tmpCounts = 1 
	else 
	 set @tmpCounts = @Counts 

	 --取得分页总数 
	 set @pageCount=(@tmpCounts+@pageSize-1)/@pageSize 

	 /**//**//**//**当前页大于总页数 取最后一页**/ 
	 if @page>@pageCount 
	 set @page=@pageCount 

	 --/*-----数据分页2分处理-------*/ 
	 declare @pageIndex int --总数/页大小 
	 declare @lastcount int --总数%页大小 

	 set @pageIndex = @tmpCounts/@pageSize 
	 set @lastcount = @tmpCounts%@pageSize 
	 if @lastcount > 0 
	 set @pageIndex = @pageIndex + 1 
	 else 
	 set @lastcount = @pagesize 

	 --//***显示分页 
	 if @strCondition is null or @strCondition='' --没有设置显示条件 
	 begin 
	 if @pageIndex<2 or @page<=@pageIndex / 2 + @pageIndex % 2 --前半部分数据处理 
	 begin 
	 if @page=1 
		 set @strTmp=@SqlSelect+' top '+ CAST(@pageSize as VARCHAR(10))+' '+ @fldName+' from '+@tblName 
		 +' order by '+ @fldSort +' '+ @strFSortType 
	 else 
		 begin 
			 if @Sort=1 
			 begin 
			 set @strTmp=@SqlSelect+' top '+ CAST(@pageSize as VARCHAR(10))+' '+ @fldName+' from '+@tblName 
			 +' where '+@ID+' <(select min('+ @ID +') from ('+ @SqlSelect+' top '+ CAST(@pageSize*(@page-1) as Varchar(20)) +' '+ @ID +' from '+@tblName 
			 +' order by '+ @fldSort +' '+ @strFSortType+') AS TBMinID)' 
			 +' order by '+ @fldSort +' '+ @strFSortType 
			 end 
		 else 
		 begin 
			 set @strTmp=@SqlSelect+' top '+ CAST(@pageSize as VARCHAR(10))+' '+ @fldName+' from '+@tblName 
			 +' where '+@ID+' >(select max('+ @ID +') from ('+ @SqlSelect+' top '+ CAST(@pageSize*(@page-1) as Varchar(20)) +' '+ @ID +' from '+@tblName 
			 +' order by '+ @fldSort +' '+ @strFSortType+') AS TBMinID)' 
			 +' order by '+ @fldSort +' '+ @strFSortType 
		 end 
	 end 
	 end 
	 else 
	 begin 
	 set @page = @pageIndex-@page+1 --后半部分数据处理 
	 if @page <= 1 --最后一页数据显示 
	 set @strTmp=@SqlSelect+' * from ('+@SqlSelect+' top '+ CAST(@lastcount as VARCHAR(10))+' '+ @fldName+' from '+@tblName 
	 +' order by '+ @fldSort +' '+ @strSortType+') AS TempTB'+' order by '+ @fldSort +' '+ @strFSortType 
	 else 
	 if @Sort=1 
	 begin 
	 set @strTmp=@SqlSelect+' * from ('+@SqlSelect+' top '+ CAST(@pageSize as VARCHAR(10))+' '+ @fldName+' from '+@tblName 
	 +' where '+@ID+' >(select max('+ @ID +') from('+ @SqlSelect+' top '+ CAST(@pageSize*(@page-2)+@lastcount as Varchar(20)) +' '+ @ID +' from '+@tblName 
	 +' order by '+ @fldSort +' '+ @strSortType+') AS TBMaxID)' 
	 +' order by '+ @fldSort +' '+ @strSortType+') AS TempTB'+' order by '+ @fldSort +' '+ @strFSortType 
	 end 
	 else 
	 begin 
	 set @strTmp=@SqlSelect+' * from ('+@SqlSelect+' top '+ CAST(@pageSize as VARCHAR(10))+' '+ @fldName+' from '+@tblName 
	 +' where '+@ID+' <(select min('+ @ID +') from('+ @SqlSelect+' top '+ CAST(@pageSize*(@page-2)+@lastcount as Varchar(20)) +' '+ @ID +' from '+@tblName 
	 +' order by '+ @fldSort +' '+ @strSortType+') AS TBMaxID)' 
	 +' order by '+ @fldSort +' '+ @strSortType+') AS TempTB'+' order by '+ @fldSort +' '+ @strFSortType 
	 end 
	 end 
	 end 

	 else --有查询条件 
	 begin 
	 if @pageIndex<2 or @page<=@pageIndex / 2 + @pageIndex % 2 --前半部分数据处理 
	 begin 
	 if @page=1 
	 set @strTmp=@SqlSelect+' top '+ CAST(@pageSize as VARCHAR(10))+' '+ @fldName+' from '+@tblName 
	 +' where ' + @strCondition + ' order by '+ @fldSort +' '+ @strFSortType 
	 else if(@Sort=1) 
	 begin 
	 set @strTmp=@SqlSelect+' top '+ CAST(@pageSize as VARCHAR(10))+' '+ @fldName+' from '+@tblName 
	 +' where '+@ID+' <(select min('+ @ID +') from ('+ @SqlSelect+' top '+ CAST(@pageSize*(@page-1) as Varchar(20)) +' '+ @ID +' from '+@tblName 
	 +' where ' + @strCondition +' order by '+ @fldSort +' '+ @strFSortType+') AS TBMinID)' 
	 +' and '+ @strCondition +' order by '+ @fldSort +' '+ @strFSortType 
	 end 
	 else 
	 begin 
	 set @strTmp=@SqlSelect+' top '+ CAST(@pageSize as VARCHAR(10))+' '+ @fldName+' from '+@tblName 
	 +' where '+@ID+' >(select max('+ @ID +') from ('+ @SqlSelect+' top '+ CAST(@pageSize*(@page-1) as Varchar(20)) +' '+ @ID +' from '+@tblName 
	 +' where ' + @strCondition +' order by '+ @fldSort +' '+ @strFSortType+') AS TBMinID)' 
	 +' and '+ @strCondition +' order by '+ @fldSort +' '+ @strFSortType 
	 end 
	 end 
	 else 
	 begin 
	 set @page = @pageIndex-@page+1 --后半部分数据处理 
	 if @page <= 1 --最后一页数据显示 
	 set @strTmp=@SqlSelect+' * from ('+@SqlSelect+' top '+ CAST(@lastcount as VARCHAR(10))+' '+ @fldName+' from '+@tblName 
	 +' where '+ @strCondition +' order by '+ @fldSort +' '+ @strSortType+') AS TempTB'+' order by '+ @fldSort +' '+ @strFSortType 
	 else if(@Sort=1) 
	 set @strTmp=@SqlSelect+' * from ('+@SqlSelect+' top '+ CAST(@pageSize as VARCHAR(10))+' '+ @fldName+' from '+@tblName 
	 +' where '+@ID+' >(select max('+ @ID +') from('+ @SqlSelect+' top '+ CAST(@pageSize*(@page-2)+@lastcount as Varchar(20)) +' '+ @ID +' from '+@tblName 
	 +' where '+ @strCondition +' order by '+ @fldSort +' '+ @strSortType+') AS TBMaxID)' 
	 +' and '+ @strCondition+' order by '+ @fldSort +' '+ @strSortType+') AS TempTB'+' order by '+ @fldSort +' '+ @strFSortType 
	 else 
	 set @strTmp=@SqlSelect+' * from ('+@SqlSelect+' top '+ CAST(@pageSize as VARCHAR(10))+' '+ @fldName+' from '+@tblName 
	 +' where '+@ID+' <(select min('+ @ID +') from('+ @SqlSelect+' top '+ CAST(@pageSize*(@page-2)+@lastcount as Varchar(20)) +' '+ @ID +' from '+@tblName 
	 +' where '+ @strCondition +' order by '+ @fldSort +' '+ @strSortType+') AS TBMaxID)' 
	 +' and '+ @strCondition+' order by '+ @fldSort +' '+ @strSortType+') AS TempTB'+' order by '+ @fldSort +' '+ @strFSortType 
	 end 
	 end 

	------返回查询结果----- 
	--print @strTmp 
	set @SQLOUT = @strTmp
	--exec sp_executesql @strTmp 
	--select datediff(ms,@timediff,getdate()) as 耗时 
	SET NOCOUNT OFF
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 money  NULL,
	fAmount money  NULL,
	fNewBalance money  NULL,
	fFee1 money  NULL,
	fFee2 money  NULL,
	fFee3 money  NULL,
	fFee4 money  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


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 money  NULL,    
 fAmount money  NULL,    
 fNewBalance money  NULL,    
 fFee1 money  NULL,   
 fFee2 money  NULL,    
 fFee3 money  NULL,    
 fFee4 money  NULL,     
 fDiscount money  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


create procedure dbo.UP_Report_Cns_SaveAndTakeRec 
    @strWhere varchar(1000),
  	@BeginDate datetime,
  	@EndDate datetime,
  	@QType int 
  	as
DECLARE @strB varchar(19)
DECLARE @strE varchar(19)
SET @strB=datename(yyyy, @BeginDate)+'-'+datename(mm, @BeginDate)+'-'+datename(dd, @BeginDate)+' '+'00:00:00'
SET @strE=datename(yyyy, @EndDate)+'-'+datename(mm, @EndDate)+'-'+datename(dd, @EndDate)+' '+'23:59:59'


DECLARE @strsql nvarchar(1000)
DECLARE @TmpWhere nvarchar(500)
DECLARE @ConsWhere nvarchar(100)
SET @TmpWhere=''
IF (@strWhere<>'')
BEGIN 
	SET @TmpWhere = '账号 IN (SELECT FAccountID FROM T_B_Employee WHERE '+@strWhere+') and ' 
END

IF @Qtype=0
BEGIN
	SET @strsql='SELECT 姓名, 工号, 账号, 卡号, 部门, 发生时间 as 存款时间, 
		原余额, 消费额 as 存款额, 现余额 as 当时余额, 操作员
		FROM dbo.V_B_OperatorRec
		Where '+@TmpWhere+' 消费类型编码 in (1)  and (发生时间>='''+@strB+''' and 发生时间<='''+@strE+''') ' 
END ELSE 
IF @Qtype=1
BEGIN
	SET @strsql='SELECT 姓名, 工号, 账号, 卡号, 部门, 发生时间 as 取款时间, 
		原余额, 消费额 as 取款额, 现余额 as 当时余额, 操作员
		FROM dbo.V_B_OperatorRec
		Where '+@TmpWhere+' 消费类型编码 in (2)  and (发生时间>='''+@strB+''' and 发生时间<='''+@strE+''') ' 
END ELSE 
IF @QType=2
BEGIN
	SET @strsql='SELECT 姓名, 工号, 账号, 卡号, 部门, 发生时间 as 存取时间, 
		CASE WHEN 消费类型编码=1 THEN ''存款'' ELSE ''取款'' END as 操作, 原余额, 
		CASE WHEN 消费类型编码=1 THEN 消费额 ELSE 0 END as 存款额,
		CASE WHEN 消费类型编码=2 THEN 消费额 ELSE 0 END as 取款额, 
		现余额 as 当时余额, 操作员
		FROM dbo.V_B_OperatorRec
		Where '+@TmpWhere+' 消费类型编码 in (1,2)  and (发生时间>='''+@strB+''' and 发生时间<='''+@strE+''') '
END ELSE 
IF @Qtype=3
BEGIN
	SET @strsql='SELECT 姓名, 工号, 账号, 部门, sum(存款次数) as 存款次数, sum(存款额) as 存款总额, 
		sum(取款次数) as 取款次数, sum(取款额) as 取款总额 
		FROM
		(SELECT 姓名, 工号, 账号, 部门, Count(*) as 存款次数, Sum(消费额) as 存款额, 0 as 取款次数, 0 as 取款额	
		FROM dbo.V_B_OperatorRec
		Where '+@TmpWhere+' 消费类型编码 =1  and (发生时间>='''+@strB+''' and 发生时间<='''+@strE+''') 
		GROUP BY 姓名, 工号, 账号, 部门
		UNION
		SELECT 姓名, 工号, 账号, 部门, 0 as 存款次数, 0 as 存款额, Count(*) as 取款次数, Sum(消费额) as 取款额
		FROM dbo.V_B_OperatorRec
		Where '+@TmpWhere+' 消费类型编码 =2  and (发生时间>='''+@strB+''' and 发生时间<='''+@strE+''') 
		GROUP BY 姓名, 工号, 账号, 部门) a
		GROUP BY 姓名, 工号, 账号, 部门'
END
--print @strsql
exec sp_executesql @strsql
go


create procedure dbo.UP_Report_Cns_SysAccount 
    @Station varchar(2),
    @OperType int,
    @BeginDate varchar(20),
    @EndDate varchar(20) 
    as
begin
declare @Where nvarchar(1000)
declare @sSQL  nvarchar(3000)
DECLARE @strB varchar(19)
DECLARE @strE varchar(19)
SET @strB=datename(yyyy, @BeginDate)+'-'+datename(mm, @BeginDate)+'-'+datename(dd, @BeginDate)+' 00:00:00'
SET @strE=datename(yyyy, @EndDate)+'-'+datename(mm, @EndDate)+'-'+datename(dd, @EndDate)+' 23:59:59'


if @OperType = 1 
  Set @Where = 'WHERE fBeginDate >= ''' + @strB + ''' and  fBeginDate <= ''' + @strE + ''''  
else if @OperType = 2   
  Set @Where = 'WHERE fEndDate >= ''' + @strB + ''' and  fEndDate <= ''' + @strE + ''''
else
  Set @Where = 'WHERE fOperDate >= ''' + @strB + ''' and  fOperDate <= ''' + @strE + ''''    
  
  
Set @sSQL = ' SELECT [fid], [fOperName], [fBeginDate], [fEndDate], [fOperDate], [fOAcount], ' +
			'	   [fOAcountMoney], [fNAcount], [fNAcountMoney], [fConsCount], [fConsMoney], [fkhCount], ' +
			'	   [fKhtlSum], [fKhDpsit], [fKhPndge], [fKhManage], [fChCount], [fChtlSum], ' + 
			'	   [fChMoney], [fChPndge], [fGsCount], [fGsPndge], [fJgCount], [fJgPndge], ' +
			'	   [fSvCount], [fSvPndge], [fSvtlSum], [fTkCount], [fTktlSum], [fHkCount], ' +
			'	   [fHkPndge], [fBkCount], [fBktlSum], [fBkPndge], [fJcCount], [fJctlSum], ' +
			'	   [fSbCount], [fSbtlSum], [fCheck], [fCheckOperName], [fCheckDate], [fRecKey] ' +
			'  FROM [T_C_SysAccount] ' + @Where
			
 --print @sSQL
 exec(@sSQL)			
end
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


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


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


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


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


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


create procedure dbo.UP_Report_Cns_Total_DeptMeal 
       @StationID   varchar(2),    -- 工作站；传值，工作站名称，只能传如一个工作站名称  
       @BegDateTime varchar(20),   --开始查询日期  
       @EndDateTime varchar(20),   --结束查询日   
       @PurseSum    varchar(1)     --钱包是否汇总统计 0- 否 1- 是 
       as
BEGIN  
 declare @VirtualAccountID varchar(40)  
 set @VirtualAccountID='00000000'  
 declare @STRSQL varchar(8000),  
   @iRet int,  
   @sRet varchar(300),  
   @strB varchar(30),  
   @strE varchar(30),
   @FieldStr1 varchar(1024),
   @FieldStr2 varchar(1024),
   @FieldStr3 varchar(1024),
   @FieldStr4 varchar(1024)    
     
 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  
  SET @FieldStr1=''
  SET @FieldStr2=''
  set @FieldStr3=''
  set @FieldStr4=''
  if @PurseSum='0'
  BEGIN
    SET @FieldStr1=' A.fPurseCode AS 钱包编码,A.fPurseName AS 钱包名称,'
    SET @FieldStr2=' ,C.fPurseCode,C.fPurseName '
    SET @FieldStr3=' ,A.fPurseCode,A.fPurseName '
    set @FieldStr4=' ,钱包名称'
  END
  
  SET @STRSQL =  
  
  'select  编号,名称,[消费|次数],[消费|金额],[存款|次数], [存款|金额],[取款|次数],[取款|金额]'+@FieldStr4+',[签字]
  
   from (select a.fDeptCode as 编号,max(b.fDeptName) 名称 , sum(consCount) as [消费|次数],  
  sum(consfare) as [消费|金额],sum(svcount) as [存款|次数],sum(svmoney) as [存款|金额],  
  sum(tkcount) as [取款|次数],sum(tkmoney) as [取款|金额],'+@FieldStr1+'    
  '' '' as [签字]   
  from   
  (  
  select R.fDeptCode'+@FieldStr2+', 
        
        Sum(case when R.fRecType in(0,17) then 1 when R.fRecType=8 then -1 else 0 end) as consCount,  
        sum(case when R.fRecType in(0,17) then R.fAmount  when R.fRecType=8 then -R.fAmount else 0.00 end) as consfare,  
        Sum(case when R.fRecType in(1,28) then 1 else 0 end) as svcount,  
        sum(case when R.fRecType in(1,28) then R.fAmount else 0.00 end) as svmoney,  
        Sum(case when R.fRecType in(2,30) then 1 else 0 end) as tkcount,  
        sum(case when R.fRecType in(2,30) then R.fAmount else 0.00 end) as tkmoney
  from ' +CHAR(13)+  
  @sRet +CHAR(13)+  
  ' LEFT JOIN T_B_PurseCode C ON R.fPurseID=C.fPurseCode'+
   ' where R.fSettleTime >= ''' + @strB + ''' AND R.fSettleTime <= ''' +@strE + ''' AND R.fAccountID <> '''+@VirtualAccountID + '''  
  group by R.fDeptCode'+@FieldStr2+'    
  ) as a left join T_B_Dept b on a.fDeptCode = b.fDeptCode  
   group by a.fDeptCode'+@FieldStr3+') t'
 end  
  print @STRSQL  
  exec(@STRSQL)   
END
go


create procedure dbo.UP_Report_Cns_Total_EmployeeMeal 
      @Station     varchar(20),  -- 工作站；  
      @BegDateTime varchar(20),  --开始查询日期  
      @EndDateTime varchar(20),  --结束查询日  
      @DeptCode varchar(40)='',--部门  
      @AccountWhere varchar(200)='' --查询人员的条件 
      as
BEGIN  
 declare @VirtualAccountID varchar(40)  
 set @VirtualAccountID='00000000'  
 declare @STRSQL varchar(8000),  
   @iRet int,  
   @sRet varchar(300),  
   @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'  
 EXEC UP_R_CheckTime @strB, @strE, 1, @iRet output, @sRet output   
 if @iRet = -9999 OR @sRet = ''  
 begin  
  SET @STRSQL = 'SELECT ''查询表无效-查询表范围超期'' AS [返回信息]'  
  --print @STRSQL     
  exec(@STRSQL)  
 end  
 ELSE  
 begin  
  Create table #tmp1(  
     [fAccountid]    [varchar](20) NULL, 
     [fEmployeeCode] [varchar](20) NULL,   
     [fName]         [varchar](20) NULL,  
     [fDeptName]     [varchar](50) NULL  
  ) ON [PRIMARY]  
     declare @AccWhere varchar(500)  
     if @AccountWhere <> ''  
       Set @AccWhere = ' Where ' + @AccountWhere  
     else  
       Set @AccWhere = ' Where 1=1 '  
       
     if @DeptCode <> ''  
       Set @AccWhere = @AccWhere + ' and fDept like ''' +@DeptCode + '%'' '  
         
  -------------------------------  
  SET @STRSQL=      
        ' insert into #tmp1 (fAccountid,fEmployeeCode,fName,fDeptName)  
          select  E.fAccountID,e.fEmployeeCode ,E.fName, D.fDeptName  
      from  (SELECT fAccountID,fEmployeeCode, fName, fDept from T_B_Employee ' + @AccWhere + ') E Left join   
     T_B_Dept D on E.fDept = D.fDeptCode '  
  -- print  @STRSQL  
  exec(@STRSQL)    
  --------------------------------   
  Create table #tmp2(  
     [fAccount_id] [varchar](20) NULL, 
     [fEmployeeCode] [varchar](20) NULL,  
  [fMeal_id] [varchar](5) NULL,  
  [Cons_Fare] [money]  NULL,  
  [constimes] [int] NULL,  
  ) ON [PRIMARY]  
  
  SET @STRSQL=  
  'INSERT INTO #tmp2   
   select fAccount_id,fEmployeeCode,fMeal_id,sum(fCons_Fare) as Cons_Fare,count(*) as constimes  
   from ' + @sRet + ' Left join V_B_SitePos P on R.fPos_id = P.fPosId left join T_B_Employee e on r.fAccount_id=e.fAccountID 
   where R.fAccount_id <> ''' + @VirtualAccountID + ''' AND P.fPosType in (1,4) and R.fCons_State in(0,8,17)  
   AND R.fSettleTime >= ''' + @strB + ''' AND R.fSettleTime <= ''' + @strE + '''   
   group by fMeal_id,fAccount_id,fEmployeeCode'  
  -- print @STRSQL  
  exec(@STRSQL)

   --------------------------------  
  select fMeal_Name,a.fEmployeeCode as 工号,a.fMeal_id,a.fAccount_id,Cons_Fare,constimes,  
      fName as 姓名,fDeptName as 部门  
    into #tmp3  
    from #tmp2 a  left join  
    T_B_MealSet b on a.fMeal_id =b.fMeal_Id  left join  
    #tmp1 c on a.fAccount_id = c.fAccountID  
    where fMeal_Name<>''  
  -------------------------------------------  
  declare  curMeal cursor for  
  select  fMeal_Id,fMeal_Name from T_B_MealSet  
  declare @MealName varchar(20),  
    @MealID varchar(3),  
    @MealCount smallint  
  open curMeal    
  fetch next  from curMeal into @MealID,@MealName  
  select @STRSQL='select 部门,工号,姓名',@MealCount=0    
  while @@fetch_status=0    
  begin  
   select @STRSQL=@STRSQL+  
     ', sum(case when fMeal_id='''+@MealID+''' then constimes else 0 end) as '''+@MealName+'|份数'''+char(13)+  
     ', sum(case when fMeal_id='''+@MealID+''' then Cons_Fare else 0 end) as '''+@MealName+'|金额'''+char(13),             
       @MealCount=@MealCount+1      
       fetch next from curMeal into  @MealID,@MealName    
  end  
  close curMeal  
  deallocate  curMeal  
  select @STRSQL = @STRSQL + ',sum(constimes) as ''总份数'',sum(Cons_Fare) as ''总金额'''+char(13)  
  select @STRSQL=@STRSQL+  
    'from #tmp3 '+  
    'where 姓名<>'''''+char(13)+  
    'group by 部门,工号,姓名 order by 部门,工号'    
  -- print @STRSQL     
  exec(@STRSQL)  
  --select * from #tmp1  
  --select * from #tmp2  
  --select * from #tmp3  
  drop table #tmp2  
  drop table #tmp1  
  drop table #tmp3  
  -------------------------------------------  
 end  
END
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


create procedure dbo.UP_Report_Cns_Total_MealAccount 
       @STATIONID   varchar(20),  -- 工作站；传值，工作站名称，只能传入一个工作站名称  
       @BegDateTime varchar(20),  --开始查询日期  
       @EndDateTime varchar(20),  --结束查询日  
       @AccountID   varchar(30)   --账号 
       as
begin  
Declare @colstr varchar(1024),   
        @sqlstr varchar(8000),  
	    @strB varchar(30),  
	    @strE varchar(30),  
	    @iRet int,
	    @i int,   
        @sRet varchar(1000)  
select  @sqlstr   = '',  @colstr   = '',   @i=1  
  
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, 4, @iRet output, @sRet output  
if @iRet = -9999 OR @sRet = ''  
  BEGIN  
    SET @sqlstr = 'SELECT ''查询表无效-查询表范围超期'' AS [返回信息]'  
  END  
  ELSE  
  BEGIN    
  declare curMeal cursor for  
  select  fMeal_id,fMeal_Name from T_B_MealSet  order by fMeal_id
  declare @MealName varchar(20),  
    @MealID varchar(3)  
  open curMeal  
  fetch next  from curMeal into @MealID,@MealName  
 
  while @@fetch_status = 0  
  begin  
    SET @colstr=@colstr+',SUM(R.fMeal'+CAST(@i as varchar(1))+'Money) as ['+@MealName+'|金额],SUM(R.fMeal'+CAST(@i as varchar(1))+'Count) as ['+@MealName+'|次数]'
    SET @i=@i+1
    fetch next from curMeal into @MealID,@MealName  
  end  
  close curMeal  
  deallocate  curMeal  
  
   SET @sqlstr='select  B.fAccountID 账号,
					   B.fName 姓名,
					   C.fDeptName 部门名称,
					   D.fPurseName 钱包名称
					   '+@colstr+',
					   SUM(R.fDayCount) 合计次数,
					   SUM(R.fDayMoney) 合计金额
				    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_PurseCode D ON R.fPurseID=D.fPurseCode 
				  where R.fDate>= '''+@BegDateTime+''' and R.fDate <='''+@EndDateTime+''' and r.fAccountID='''+@AccountID+'''  and b.fCard_State not in (3,4) 
				  GROUP BY B.fAccountID,B.fName, C.fDeptName,D.fPurseName ORDER BY D.fPurseName '
  END  
 print @sqlstr  
 exec(@sqlstr)  
 end
go


create procedure dbo.UP_Report_Cns_Total_MealBZ 
       @Station     varchar(20),  -- 工作站；
       @BegDateTime varchar(20),  --开始查询日期
       @EndDateTime varchar(20),  --结束查询日
       @St_Id varchar(40)=''      --营业组 
       as
BEGIN
	declare @STRSQL varchar(8000),
			@iRet int,
			@sRet varchar(300),
			@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' 
	set @STRSQL = 
	'select C.fStation_Name, C.fSt_Name, b.fMeal_Name,b.fMeal_Id, '+ char(13) + 
	'sum([消费|次]) as PosFare_Count,sum([消费|金额] + [纠错|金额]) as PosFare_Ze, Sum([计次|次]) as JcCount '+ char(13) + 
	'into #temp1        '+ char(13) + 
	'from V_C_SUM_Pos A inner join T_B_MealSet B on A.fMealID = B.fMeal_Id '+ char(13) + 
	'                      inner join (                       '+
	'select a.fStation_Id, A.fStation_Name, B.fSt_Id, fSt_Name, fBz_Id, fBz_Name, fPosID, fPosName '+ char(13) + 
	'from T_B_Station A inner join T_B_Stbm B on A.fStation_Id = B.fStation_Id '+ char(13) + 
	'     inner join T_B_Bzbm C on A.fStation_Id = C.fStation_Id and b.fSt_Id = c.fSt_Id '+ char(13) + 
	'     inner join T_B_Pos D on D.fSiteID = C.fBz_Id   '+        char(13) + 
	'                      ) C on a.fPosID = c.fPosID '+ char(13) + 
	'where A.fDate >=''' + @strB + ''' and '+ char(13) + 
	'      A.fDate <=''' + @strE + ''' and '+ char(13) + 
	'   (c.fStation_Id like ''' + @Station + '%'') and '+ char(13) + 
	'   (c.fSt_Id like ''' + @St_Id + '%'') '+ char(13) + 
	'group by C.fStation_Name, C.fSt_Name, b.fMeal_Name,b.fMeal_Id'
	  
	  --select * From #temp1 
	 declare  curMeal cursor for
	 select  fMeal_Id,fMeal_Name from T_B_MealSet
	 declare @MealName varchar(20),
			 @MealID varchar(3),
			 @MealCount smallint
	         
	 open curMeal
	 fetch next  from curMeal into @MealID,@MealName
	 select @STRSQL = @STRSQL + char(13) + 'select fStation_Name as 工作站, fSt_Name as 营业组'
	 while @@fetch_status = 0
	 begin
		select @STRSQL = @STRSQL+',sum(case when fMeal_Id = ''' + @MealID + 
							  ''' then PosFare_Count else 0 end) as ''' + @MealName + '|份数''' +char(13)
							  + ',sum(case when fMeal_Id=''' + @MealID + 
							  ''' then PosFare_Ze else 0 end) as ''' + @MealName + '|金额''' + char(13)
							  + ',sum(case when fMeal_Id=''' + @MealID + 
							  ''' then JcCount else 0 end) as ''' + @MealName + '|计次''' + char(13),
	   @MealCount=@MealCount+1 
	   fetch next from curMeal into @MealID,@MealName
	 end
	 close curMeal
	 deallocate  curMeal
	 SET @STRSQL = @STRSQL + ',sum(PosFare_Count) as 合计份数,sum(PosFare_Ze) as 合计金额, Sum(JcCount) as 合计计次' + char(13) + 
								'from #temp1' + char(13) + 
								'group by fStation_Name, fSt_Name' + char(13) + 
								'drop table #temp1'
	--print @STRSQL
	 exec(@STRSQL)
END
go


create procedure dbo.UP_Report_Cns_Total_MealDays 
       @StationID   varchar(2),  -- 工作站；        
       @BegDateTime varchar(20),  --开始查询日期        
       @EndDateTime varchar(20),  --结束查询日        
       @posname    varchar(20),   --终端机名称        
       @bzname     varchar(40),   --班组名称     
       @SiteName   varchar(50)    --营业组 
       as
BEGIN        
 Declare @colstr varchar(256),        
   @acolstr varchar(256),        
   @colstrA varchar(256),        
   @acolstrB varchar(256),        
   @acolstrC varchar(256),        
   @strPOS varchar(50),        
   @strPOSA varchar(50) ,        
   @strBZ varchar(50),    
   @strST varchar(50)          
 declare @STRSQL varchar(8000),        
   @iRet int,        
   @sRet varchar(300),        
   @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'        
 EXEC UP_R_CheckTime @strB, @strE, 1, @iRet output, @sRet output        
 if @iRet = -9999 OR @sRet = ''        
  SET @STRSQL = 'SELECT ''查询表无效-查询表范围超期'' AS [返回信息]'        
 ELSE        
 begin        
        
  select @colstr = '',        
      @acolstr = '',        
      @colstrA = '',        
      @acolstrB = '',        
      @acolstrC = '',     
      @strST    =''       
                 
  --班组条件        
   if @bzname <> ''        
   begin        
     SET @colstr  = ',fBz_Id,fBz_Name'        
     SET @acolstr = ',fBz_Name as 班组'        
     SET @colstrA  = ',fBz_Id,fBz_Name'        
     SET @acolstrB = ',fBz_Name as 班组'            
     SET @acolstrC = ',fBz_Id,fBz_Name'        
     SET @strBZ = '    and fBz_Id like ''' + @bzname + '''' + char(13)        
   end        
   else        
     SET @strBZ = ''                   
        
           
   --终端机条件        
   if @posname <> ''        
   begin        
     SET @colstr = @colstr+',A.fPosID,fPosName'        
     SET @acolstr = @acolstr+',fPosName as POS机号'        
     SET @colstrA = @colstrA+',R.fPosid,fPosName'        
     SET @acolstrB = @acolstrB+',fPosName as POS机号'        
     SET @acolstrC = @acolstrC + ',R.fPosID as fPosID,fPosName'        
     SET @strPOS = '    and R.fPosID like ''' + @posname + '''' + char(13)        
     SET @strPOSA = '    and R.fPosID like ''' + @posname + '''' + char(13)        
   end        
   else        
   begin        
     SET @strPOS = ''        
     SET @strPOSA = ''        
   end        
       
   --营业组条件    
       
   if  @SiteName<>''    
   begin    
     SET @colstr = @colstr+',fSt_ID,fSt_Name'        
     SET @acolstr = @acolstr+',fSt_Name as 营业组'        
     SET @colstrA = @colstrA+',f.fSt_ID,f.fSt_Name '        
     SET @acolstrB = @acolstrB+',f.fSt_Name 营业组 '        
     SET @acolstrC = @acolstrC + ',f.fSt_ID,f.fSt_Name'     
     set @strST =' and f.fSt_ID like '''+@SiteName+''''+ char(13)       
   end     
       
   select @STRSQL=        
  'select fMeal_Name, fMealid, SUM(PosFare_Count) as PosFare_Count, SUM(PosFare_Ze) as PosFare_Ze, Pos_Date, sum(ConsPeopleRate) as ConsPeopleRate, Sum(JcCount) as JcCount ' + @colstr + char(13)+        
  'into #tmp1 ' + char(13)+        
  'from ' + char(13)+        
  '( ' + char(13)+        
  'select fMeal_Name, a.fMealid, PosFare_Count, PosFare_Ze,Pos_Date, ' + char(13)+        
  'cast(cast(ConsPeopleCount as decimal(18,2)) / cast(TotalPeopleCount as decimal(18,2)) as decimal(18,2)) * 100  as ''ConsPeopleRate'', JcCount '+ @colstr + char(13)+        
  'from  ' + char(13)+        
  '( ' + char(13)+        
  'select fMeal_Name, fMealid,sum(case when fPurseType=0 and fRecType in (0,17) then 1 when fPurseType=0 and fRecType in (8) then -1 else 0 end ) PosFare_Count ,    
  sum(case when fPurseType=1 then fAmount else 0 end) JcCount,     
  sum(case when fPurseType=0 then fAmount else 0 end ) PosFare_Ze, count(distinct fAccountID) as ConsPeopleCount,TotalPeopleCount=isnull((select COUNT(*) as TotalPeopleCount'+  
  +' from T_B_Employee where fcard_state not in (3)),0), fCons_Time as Pos_Date '+ @colstr + char(13)+        
  'from  ' + char(13)+        
'( ' + char(13)+        
  'select  R.fAccountID,C.fMeal_Name,R.fMealID,convert(char(10),R.fCreateTime,120) as fCons_Time ,(case when R.fRecType in(0,17) then  r.fAmount else 0 end)-  
  (case when R.fRecType in(8) then  r.fAmount else 0 end) fAmount ,r.fRecType,g.fPurseType  ' +  @acolstrC + char(13)+        
  'from ' + CHAR(13) +        
  @sRet +        
  ' inner join T_B_Employee b on R.fAccountID = b.fAccountID ' + char(13)+        
  ' left join T_B_MealSet c on R.fMealID = c.fMeal_id ' + char(13)+        
  ' left join T_B_Pos d on R.fPosID = d.fPosID ' + char(13)+        
  ' left join T_B_Bzbm e on d.fSiteID = e.fBz_Id ' + char(13)+     
  ' left join t_b_stbm f on e.fSt_ID=f.fSt_ID'+      
  ' left join T_B_PurseCode g on r.fPurseID=g.fPurseCode'+     
  ' where R.fRecType in(0,8,17) AND R.fSettleTime>=''' + @strB + '''' + char(13)+     
  ' and b.fCard_State not in (3)'+       
  '  AND R.fSettleTime<=''' + @strE + ''''+ char(13)+        
  @strPOSA+        
  @strBZ+      
  @strST+        
  ') a group by fMealid,fCons_Time, fMeal_Name'+ @colstr + char(13)+        
  ') a ' + char(13)+        
  ') a group by fMeal_Name, fMealid,Pos_Date '+ @colstr        
        
   declare @fMealCount int        
   select @fMealCount = isnull(count(*)* 100, 0)  from T_B_MealSet        
           
   declare  curMeal cursor for        
   select  fMeal_Id,fMeal_Name from T_B_MealSet        
   declare @MealName varchar(20),        
    @MealID varchar(3),        
    @MealCount smallint        
   open curMeal        
   fetch next  from curMeal into @MealID,@MealName        
   select @STRSQL = @STRSQL+char(13)+'select Pos_Date as 消费日期',@MealCount=0        
   while @@fetch_status = 0        
   begin        
     select @STRSQL = @STRSQL + ',sum(case when fMealid = '''+@MealID + ''' then PosFare_Count else 0 end) as ''' + @MealName + '|份数''' +char(13)        
         + ',sum(case when fMealid=''' + @MealID + ''' then PosFare_Ze else 0 end) as ''' + @MealName + '|金额''' + char(13)        
         + ',sum(case when fMealid=''' + @MealID + ''' then JcCount else 0 end) as ''' + @MealName + '|计次''' + char(13)        
         + ',sum(case when fMealid=''' + @MealID + ''' then ConsPeopleRate else 0 end) as ''' + @MealName + '|就餐率(%)''' + char(13),        
     @MealCount=@MealCount+1         
     fetch next from curMeal into @MealID,@MealName        
   end         
   close curMeal        
   deallocate  curMeal        
   select @STRSQL = @STRSQL + ',sum(PosFare_Count) as 合计份数,sum(PosFare_Ze) as 合计金额, Sum(JcCount) as 合计计次 ' + char(13)              
          + ',cast(sum(ConsPeopleRate)/' + cast(@fMealCount as varchar(10)) + ' * 100 as decimal(18,2))as ''日就餐率(%)'''  + char(13)                             
          + @acolstr        
          + ' from #tmp1 a' + char(13)         
          + ' group by Pos_Date' + @colstr + char(13)         
          + ' drop table #tmp1'        
  end        
 print @STRSQL        
 exec(@STRSQL)        
END
go


create procedure dbo.UP_Report_Cns_Total_MealDept 
       @STATIONID   varchar(20),  -- 工作站；传值，工作站名称，只能传入一个工作站名称  
       @BegDateTime varchar(20),  --开始查询日期  
       @EndDateTime varchar(20) --结束查询日 
       as
begin  
Declare @colstr varchar(1024),  
        @sqlstr varchar(8000),  
	    @strB varchar(30),  
	    @strE varchar(30),  
	    @iRet int,
	    @i int,   
        @sRet varchar(1000)  
select  @sqlstr   = '',  @colstr   = '',   @i=1  
  
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, 4, @iRet output, @sRet output  
if @iRet = -9999 OR @sRet = ''  
  BEGIN  
    SET @sqlstr = 'SELECT ''查询表无效-查询表范围超期'' AS [返回信息]'  
  END  
  ELSE  
  BEGIN    
  
  declare curMeal cursor for  
  select  fMeal_id,fMeal_Name from T_B_MealSet  order by fMeal_id
  declare @MealName varchar(20),  
    @MealID varchar(3)  
  open curMeal  
  fetch next  from curMeal into @MealID,@MealName  
 
  while @@fetch_status = 0  
  begin  
    SET @colstr=@colstr+',SUM(R.fMeal'+CAST(@i as varchar(1))+'Money) as ['+@MealName+'|金额],SUM(R.fMeal'+CAST(@i as varchar(1))+'Count) as ['+@MealName+'|次数]'
    SET @i=@i+1
    fetch next from curMeal into @MealID,@MealName  
  end  
  close curMeal  
  deallocate  curMeal  
  
   SET @sqlstr='select C.fDeptName 部门名称,
					   D.fPurseName 钱包名称
					   '+@colstr+',
					   SUM(R.fDayCount) 合计次数,
					   SUM(R.fDayMoney) 合计金额
				    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_PurseCode D ON R.fPurseID=D.fPurseCode 
				  where R.fDate>= '''+@BegDateTime+''' and R.fDate <='''+@EndDateTime+''' and b.fCard_State not in (3,4) 
				  GROUP BY C.fDeptName,D.fPurseName ORDER BY D.fPurseName '
  END  
 print @sqlstr  
 exec(@sqlstr)  
 end
go


create procedure dbo.UP_Report_Cns_Total_MealDeptAccount 
       @STATIONID   varchar(20),  -- 工作站；传值，工作站名称，只能传入一个工作站名称  
       @BegDateTime varchar(20),  --开始查询日期  
       @EndDateTime varchar(20),  --结束查询日  
       @Dept        varchar(4096)   --部门编号 
       as
begin  
Declare @colstr varchar(1024),
        @where varchar(2000),   
        @sqlstr varchar(8000),  
	    @strB varchar(30),  
	    @strE varchar(30),  
	    @iRet int,
	    @i int,   
        @sRet varchar(1000)  
select  @sqlstr   = '',  @colstr   = '',   @i=1  
  
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, 4, @iRet output, @sRet output  
if @iRet = -9999 OR @sRet = ''  
  BEGIN  
    SET @sqlstr = 'SELECT ''查询表无效-查询表范围超期'' AS [返回信息]'  
  END  
  ELSE  
  BEGIN    
  
   if(@Dept <> 'ALL') and (@Dept <> '')   
   --set @strDP = ' AND ' + @Dept + ' ' + CHAR(13)  
   Set @where = ' and b.fDept like ''' +@Dept + '%'' '  + CHAR(13)  
 else  
   set @where = ''   
  
  
  declare curMeal cursor for  
  select  fMeal_id,fMeal_Name from T_B_MealSet  order by fMeal_id
  declare @MealName varchar(20),  
    @MealID varchar(3)  
  open curMeal  
  fetch next  from curMeal into @MealID,@MealName  
 
  while @@fetch_status = 0  
  begin  
    SET @colstr=@colstr+',SUM(R.fMeal'+CAST(@i as varchar(1))+'Money) as ['+@MealName+'|金额],SUM(R.fMeal'+CAST(@i as varchar(1))+'Count) as ['+@MealName+'|次数]'
    SET @i=@i+1
    fetch next from curMeal into @MealID,@MealName  
  end  
  close curMeal  
  deallocate  curMeal  
  
   SET @sqlstr='select C.fDeptName 部门名称,
					   D.fPurseName 钱包名称
					   '+@colstr+',
					   SUM(R.fDayCount) 合计次数,
					   SUM(R.fDayMoney) 合计金额
				    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_PurseCode D ON R.fPurseID=D.fPurseCode 
				  where R.fDate>= '''+@BegDateTime+''' and R.fDate <='''+@EndDateTime+''' '+@where+' and b.fCard_State not in (3,4) 
				  GROUP BY C.fDeptName,D.fPurseName ORDER BY D.fPurseName '
  END  
 print @sqlstr  
 exec(@sqlstr)  
 end
go


create procedure dbo.UP_Report_Cns_Total_MealStation 
       @STATIONID     varchar(20),  -- 工作站；传值，工作站名称，只能传入一个工作站名称      
       @BegDateTime varchar(20),  --开始查询日期      
       @EndDateTime varchar(20),  --结束查询日      
       @Type        varchar(1),    --查询类型0--按机号进行查询统计 1--按部门进行查询统计 2--按人员进行查询统计       
       @PurseTypeStr varchar(400),  --钱包选择    
       @PurseSum varchar(1),--钱包是否汇总统计 0- 否 1- 是    
       @DeptStr  varchar(4000),--部门    
       @EmpStr   varchar(4000), --人员选择    
       @PosStr   varchar(4000) --设备选择 
       as
begin      
Declare @wherestr varchar(4000),      
        @colstr varchar(1024),      
        @ordstr varchar(1024),    
        @FieldStr1 varchar(1024),    
        @FieldStr2 varchar(1024),     
        @FieldStr3 varchar(1024),         
        @sqlstr varchar(8000),      
  @strB varchar(30),      
  @strE varchar(30),      
  @iRet int,      
        @sRet varchar(300)      
select @wherestr = '',      
       @sqlstr   = '',      
       @colstr   = '',    
       @FieldStr1='',    
       @FieldStr2='',    
       @FieldStr3='',        
       @ordstr   = ''    
      
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      
    SET @sqlstr = 'SELECT ''查询表无效-查询表范围超期'' AS [返回信息]'      
  END      
  ELSE      
  BEGIN      
 if(@STATIONID <> '')      
 begin      
   set @wherestr = ' and (r.fSiteID=''' + @STATIONID + ''')'      
 end      
 if  @PurseTypeStr<>''      
   set @wherestr = ' and '+@PurseTypeStr     
   
 if @PosStr <>''
   set @wherestr =' and '+@PosStr
     
 declare @VirtualAccountID varchar(40)      
 set @VirtualAccountID='00000000'      
     
       
 --0按机号进行查询统计      
 if(@Type = '0')      
 begin      
   --0-按钱包分开统计，1-按钱包汇总统计    
   if @PurseSum=0    
   begin    
      set @FieldStr1=',fPurseName 钱包名称'    
      set @FieldStr2=',fPurseCode,fPurseName'    
      set @FieldStr3=',G.fPurseCode,G.fPurseName'    
   end     
       
   set @colstr = ' fStation_Name as 工作站, fSt_Name as 营业组, fPosName as 消费机'    
   set @ordstr = ' fSiteID, fStation_Name, fSt_Id, fSt_Name, fPosID, fPosName'+@FieldStr2    
   set @sqlstr =       
  ' select fMeal_Name,fMealID, Sum(SumAmount) as SumAmount ,Sum(ConsCount) as ConsCount, Sum(JCAmount) as JCAmount ,Sum(JCCount) as JCCount,    
           fPosID,fPosName,fSt_Name,fSt_Id,fStation_Id fSiteID,fStation_Name' +@FieldStr2+ CHAR(13) +      
  ' into #temp1 ' + CHAR(13) +      
  ' from  ' + CHAR(13) +     
  ' ( ' + CHAR(13) +      
  ' select B.fMeal_Name,R.fMealID,sum(case when R.fRecType in (0,17) then R.fAmount else 0 end ) as SumAmount,'+    
  ' sum(case when R.fRecType in (0,17) then 1 else 0 end ) as ConsCount, ' + CHAR(13) +    
  ' sum(case when R.fRecType in (8) then R.fAmount else 0 end ) as JCAmount,'+ CHAR(13) +    
  ' sum(case when R.fRecType in (8) then 1 else 0 end ) as JCCount,'+ CHAR(13) +    
  ' c.fPosID, c.fPosName,e.fSt_Name,e.fSt_Id,f.fStation_Id,f.fStation_Name '+@FieldStr3 + CHAR(13) +      
  ' from ' +@sRet +      
  ' left join T_B_MealSet as  b on R.fMealID = b.fMeal_Id  ' + CHAR(13) +      
  ' left join T_B_Pos as c on R.fPosID = c.fPosID  ' + CHAR(13) +      
  ' left join T_B_Bzbm as d on c.fSiteID=d.fBz_Id  ' + CHAR(13) +      
  ' left join T_B_Stbm as e on d.fSt_Id = e.fSt_Id  ' + CHAR(13) +      
  ' left join T_B_Station f on e.fStation_Id = f.fStation_Id  ' + CHAR(13) +     
  ' left join T_B_PurseCode g on R.fPurseID = G.fPurseCode  ' + CHAR(13) +       
  ' where (R.fRecType in (0,8,17)) and ' +CHAR(13) +      
  '        R.fSettleTime>=''' + @strB + ''' and ' + CHAR(13) +      
  '        R.fSettleTime<=''' + @strE + ''' and ' + CHAR(13) +      
  '        R.fAccountID <> ''' + @VirtualAccountID + ''' ' + CHAR(13) +      
            @wherestr + CHAR(13) +    
  ' group by fMeal_Name,R.fMealID, c.fPosID, c.fPosName,e.fSt_Name,e.fSt_Id,f.fStation_Id,f.fStation_Name ' +@FieldStr3+    
  ') as a ' + CHAR(13) +    
  ' group by fMeal_Name,fMealID, fPosID, fPosName,fSt_Name,fSt_Id,fStation_Id,fStation_Name '+@FieldStr2     
        
 --1按部门进行查询统计        
 end else if(@Type = '1')      
 begin      
    --0-按钱包分开统计，1-按钱包汇总统计    
    if @PurseSum=0     
    begin    
      set @FieldStr1=',fPurseName 钱包名称'    
      set @FieldStr2=',fPurseCode,fPurseName'    
      set @FieldStr3=',E.fPurseCode,E.fPurseName'    
    end     
      
   if  @DeptStr<>''      
   set @wherestr = ' and '+@DeptStr     
        
   set @colstr = ' fStation_Name as 工作站, fDeptName as 部门名称 '+@FieldStr1      
   set @ordstr = ' fSiteID, fStation_Name, fDeptCode, fDeptName '+@FieldStr2      
   set @sqlstr =       
  'select fSiteID,fStation_Name, Sum(SumAmount) as SumAmount ,Sum(ConsCount) as ConsCount,Sum(JCAmount) as JCAmount ,Sum(JCCount) as JCCount, fDeptCode, fDeptName,fMeal_Name,fMealID '+@FieldStr2 + CHAR(13) +      
  'into #temp1 ' + CHAR(13) +      
  'from  ' + CHAR(13) +      
  '( ' + CHAR(13) +        
  ' select r.fSiteID,c.fStation_Name,d.fDeptCode, d.fDeptName,fMeal_Name,R.fMealID,' + CHAR(13) +    
  ' sum(case when R.fRecType in (0,17) then R.fAmount else 0 end ) as SumAmount,' + CHAR(13) +    
  ' sum(case when R.fRecType in (0,17) then 1 else 0 end ) as ConsCount, ' + CHAR(13) +    
  ' sum(case when R.fRecType in (8) then R.fAmount else 0 end ) as JCAmount,' + CHAR(13) +    
  ' sum(case when R.fRecType in (8) then 1 else 0 end ) as JCCount'+  @FieldStr3 + CHAR(13) +      
  'from  ' + CHAR(13) +      
  @sRet +      
  ' left join T_B_MealSet as  b on R.fMealID = b.fMeal_Id   ' + CHAR(13) +      
  ' left join T_B_Station c on c.fStation_Id = r.fSiteID  ' + CHAR(13) +      
  ' left join T_B_Dept d on R.fDeptCode = d.fDeptCode  ' + CHAR(13) +      
  ' left join T_B_PurseCode E on R.fPurseID = E.fPurseCode  ' + CHAR(13) +       
  ' where (R.fRecType in (0,8,17)) and  ' + CHAR(13) +      
  '        R.fSettleTime>=''' + @strB + ''' and ' + CHAR(13) +      
  '        R.fSettleTime<=''' + @strE + ''' and ' + CHAR(13) +      
  '        R.fAccountID <> ''' + @VirtualAccountID + ''' ' + CHAR(13) +        
          @wherestr + CHAR(13) +      
  '  group by r.fSiteID,c.fStation_Name,d.fDeptCode, d.fDeptName,fMeal_Name,R.fMealID '+@FieldStr3+ CHAR(13) +      
  ') as a' + CHAR(13) +       
  ' group by fSiteID,fStation_Name, fDeptCode, fDeptName,fMeal_Name,fMealID '+@FieldStr2          
 --2按人员进行查询统计      
 end else if(@Type = '2')      
 begin      
   --0-按钱包分开统计，1-按钱包汇总统计    
    if @PurseSum=0     
    begin    
      set @FieldStr1=',fPurseName 钱包名称'    
      set @FieldStr2=',fPurseCode,fPurseName'    
      set @FieldStr3=',E.fPurseCode,E.fPurseName'    
    end     
      
   if @EmpStr<>''     
   set @wherestr=@wherestr+'and  D.fAccountID in (select fAccountID from t_b_Employee where '+@EmpStr+' )'    
     
     
   set @colstr = ' fStation_Name as 工作站, fAccountID as 帐号, fName as 姓名'      
   set @ordstr = 'fSiteID, fStation_Name, fAccountID, fSerialNo, fName'+@FieldStr2      
   set @sqlstr =      
  'select fSiteID,fStation_Name, Sum(SumAmount) as SumAmount ,Sum(ConsCount) as ConsCount,Sum(JCAmount) as JCAmount ,Sum(JCCount) as JCCount, fAccountID, fName,fSerialNo,fMeal_Name,fMealID  '+@FieldStr2 + CHAR(13) +      
  'into #temp1 ' + CHAR(13) +      
  'from  ' + CHAR(13) +      
  '( ' + CHAR(13) +         
  ' select r.fSiteID,c.fStation_Name,d.fAccountID, d.fName, d.fSerialNo,fMeal_Name,R.fMealID,'+ CHAR(13) +    
  ' sum(case when R.fRecType in (0,17) then R.fAmount else 0 end ) as SumAmount,'+ CHAR(13) +    
  ' sum(case when R.fRecType in (0,17) then 1 else 0 end ) as ConsCount, ' + CHAR(13) +    
  ' sum(case when R.fRecType in (8) then R.fAmount else 0 end ) as JCAmount,'+ CHAR(13) +    
  ' sum(case when R.fRecType in (8) then 1 else 0 end ) as JCCount '+  +@FieldStr3+ CHAR(13) +      
  'from ' + CHAR(13) +      
  @sRet +      
  ' left join T_B_MealSet as  b on R.fMealID = b.fMeal_Id  ' + CHAR(13) +      
  ' left join T_B_Station c on c.fStation_Id = r.fSiteID ' + CHAR(13) +      
  ' left join T_B_Employee d on R.fAccountID = d.fAccountID ' + CHAR(13) +      
  ' left join T_B_PurseCode E on R.fPurseID = E.fPurseCode  ' + CHAR(13) +       
  ' where (R.fRecType in (0,8,17)) and ' + CHAR(13) +      
  '        R.fSettleTime>=''' + @strB + ''' and ' + CHAR(13) +      
  '        R.fSettleTime<=''' + @strE + ''' and ' + CHAR(13) +      
  '        R.fAccountID <> ''' + @VirtualAccountID + ''' ' + CHAR(13) +        
            @wherestr + CHAR(13) +      
  '  group by r.fSiteID,c.fStation_Name,d.fAccountID, d.fName, d.fSerialNo,fMeal_Name,R.fMealID '+@FieldStr3+ CHAR(13) +      
  ') as a' + CHAR(13) +       
  ' group by fSiteID,fStation_Name, fAccountID, fName,fSerialNo,fMeal_Name,fMealID '+@FieldStr2          
 end      
  declare curMeal cursor for      
  select  fMeal_id,fMeal_Name from T_B_MealSet      
  declare @MealName varchar(20),      
    @MealID varchar(3)      
  open curMeal      
  fetch next  from curMeal into @MealID,@MealName      
  select @sqlstr = @sqlstr+char(13)+'select ' + @colstr      
  while @@fetch_status = 0      
  begin      
    select @sqlstr = @sqlstr +     
    ',sum(case when fMealID=''' + @MealID + ''' then SumAmount else 0 end) as ''' + @MealName + '|消费金额''' + char(13) +       
    ',sum(case when fMealID=''' + @MealID + ''' then consCount else 0 end) as ''' + @MealName + '|消费次数''' + CHAR(13)+     
    ',sum(case when fMealID=''' + @MealID + ''' then JCAmount else 0 end) as ''' + @MealName + '|纠错金额''' + char(13) +       
    ',sum(case when fMealID=''' + @MealID + ''' then JCCount else 0 end) as ''' + @MealName + '|纠错次数''' + CHAR(13)      
         
    fetch next from curMeal into @MealID,@MealName      
  end      
  close curMeal      
  deallocate  curMeal   
    
  if @Type = '1'     
  select @sqlstr = @sqlstr + ',sum(SumAmount-JCAmount) as [合计|金额], sum(consCount-JCCount) as [合计|次数] from #temp1' + char(13) +       
       'group by ' + @ordstr + char(13) +       
       'drop table #temp1'  
  else  
   select @sqlstr = @sqlstr + ',sum(SumAmount-JCAmount) as [合计|金额], sum(consCount-JCCount) as [合计|次数]'+@FieldStr1+' from #temp1' + char(13) +       
       'group by ' + @ordstr + char(13) +       
       'drop table #temp1'        
  END      
  PRINT @sqlstr    
 exec(@sqlstr)      
 end
go


create procedure dbo.UP_Report_DZD_detail_BK 
       @Station     varchar(20),  -- 工作站；传值，工作站名称，只能传入一个工作站名称
       @BegDateTime varchar(20),  --开始查询日期
       @EndDateTime varchar(20),  --结束查询日
       @DeptCode   varchar(20),    -- 部门编号,为空查询所有部门
       @Id_TypeId   varchar(20)   --身份类型ID 
       as
begin
	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'
	DECLARE @SQL nvarchar(4000),
	        @iRet int,
	        @sRet varchar(300)
	EXEC UP_R_CheckTime @strB, @strE, 1, @iRet output, @sRet output
	if @iRet = -9999 OR @sRet = ''
	  SET @SQL = 'SELECT ''查询表无效-查询表范围超期'' AS [返回信息]'
	  /*SET @SQL = 
		'select 
		 '''' as [姓名], 
		 '''' as [学号], 
		 '''' as [部门名称],
		 '''' as [帐号],
		 '''' as [卡号], 
		 '''' as [身份类型],
		 '''' as [操作时间],
		 '''' as [补卡前金额],
		 '''' as [手续费],
		 '''' as [补卡后金额],
		 '''' as [操作员] '*/
	ELSE
	begin
	  SET @SQL =
         'select 
       b.fName as [姓名], 
       b.fEmployeeCode as [学号], 
       c.fDeptName as [部门名称],
       R.fAccount_id as [帐号],
       R.fCard_Number as [卡号], 
       f.fId_TypeName as [身份类型],
       R.fCons_Time as [操作时间],
       R.fOdd_Money as [补卡前金额],
       R.fsx_Money as [手续费],
       R.fX_Money as [补卡后金额],
       g.fOperName as [操作员]
	from ' + @sRet + CHAR(13) +
	' left join T_B_Employee b on R.fAccount_id = b.fAccountID                  
	  left join T_B_Dept c     on R.fDp_bh = c.fDeptCode 
	  left join T_B_Pos d      on R.fPos_id = d.fPosID
	  left join T_B_Station e  on R.fStation_Id = e.fStation_Id
	  left join T_B_ManType f on b.fId_TypeId = f.fId_TypeId
	  left join T_B_Manager g on R.fOper_ID = g. fOperID
	where fCons_State = 10 and
		  fSettleTime >= ''' + @strB + ''' and 
		  fSettleTime <= ''' + @strE + ''' '
	if @DeptCode <> ''
	  Set @SQL = @SQL + CHAR(13) + ' and  b.fDept like ''' + @DeptCode + '%'' '    
	if @Id_TypeId <> ''
      Set @SQL = @SQL + CHAR(13)+ ' and  b.fId_TypeId like ''' + @Id_TypeId + '%'' '
    Set @SQL = @SQL + CHAR(13)+ ' order by R.fAccount_id '	
	end
  --print @SQL
  exec sp_executesql @SQL
end
go


create procedure dbo.UP_Report_DZD_detail_CH 
       @Station     varchar(20),  -- 工作站；传值，工作站名称，只能传入一个工作站名称
       @BegDateTime varchar(20),  --开始查询日期
       @EndDateTime varchar(20),  --结束查询日
       @DeptCode   varchar(20),    -- 部门编号,为空查询所有部门
       @Id_TypeId   varchar(20)   --身份类型ID 
       as
begin
	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'
	DECLARE @SQL nvarchar(4000),
	        @iRet int,
	        @sRet varchar(300)
	EXEC UP_R_CheckTime @strB, @strE, 1, @iRet output, @sRet output
	if @iRet = -9999 OR @sRet = ''
	  SET @SQL = 'SELECT ''查询表无效-查询表范围超期'' AS [返回信息]'
	  /*SET @SQL = 
		'select 
		 '''' as [姓名], 
		 '''' as [学号], 
		 '''' as [部门名称],
		 '''' as [帐号],
		 '''' as [卡号], 
		 '''' as [身份类型],
		 '''' as [操作时间],
         '''' as [原余额], 
         '''' as [手续费],
         '''' as [开户押金],
         '''' as [现余额],       
         '''' as [操作员]'*/
	ELSE
	begin
	  SET @SQL =
         'select 
       b.fName as [姓名], 
       b.fEmployeeCode as [学号], 
       c.fDeptName as [部门名称],
       R.fAccount_id as [帐号],
       R.fCard_Number as [卡号], 
       f.fId_TypeName as [身份类型],
       R.fCons_Time as [操作时间],
       R.fOdd_Money as [原余额], 
       R.fsx_Money as [手续费],
       R.fManageMoney as [开户押金],
       R.fX_Money as [现余额],       
       g.fOperName as [操作员]
	from ' + @sRet + CHAR(13) +
	' left join T_B_Employee b on R.fAccount_id = b.fAccountID                  
	  left join T_B_Dept c     on R.fDp_bh = c.fDeptCode 
	  left join T_B_Pos d      on R.fPos_id = d.fPosID
	  left join T_B_Station e  on R.fStation_Id = e.fStation_Id
	  left join T_B_ManType f on b.fId_TypeId = f.fId_TypeId
	  left join T_B_Manager g on R.fOper_ID = g. fOperID
	where fCons_State = 7 and
		  fSettleTime >= ''' + @strB + ''' and 
		  fSettleTime <= ''' + @strE + ''' '
	if @DeptCode <> ''
	  Set @SQL = @SQL + CHAR(13) + ' and  b.fDept like ''' + @DeptCode + '%'' '    
	if @Id_TypeId <> ''
      Set @SQL = @SQL + CHAR(13)+ ' and  b.fId_TypeId like ''' + @Id_TypeId + '%'' '
    Set @SQL = @SQL + CHAR(13)+ ' order by R.fAccount_id '	
	end
  --print @SQL
  exec sp_executesql @SQL
end
go


create procedure dbo.UP_Report_DZD_detail_GS 
       @Station     varchar(20),  -- 工作站；传值，工作站名称，只能传入一个工作站名称
       @BegDateTime varchar(20),  --开始查询日期
       @EndDateTime varchar(20),  --结束查询日
       @DeptCode   varchar(20),    -- 部门编号,为空查询所有部门
       @Id_TypeId   varchar(20)   --身份类型ID 
       as
begin
	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'
	DECLARE @SQL nvarchar(4000),
	        @iRet int,
	        @sRet varchar(300)
	EXEC UP_R_CheckTime @strB, @strE, 1, @iRet output, @sRet output
	if @iRet = -9999 OR @sRet = ''
	  SET @SQL = 'SELECT ''查询表无效-查询表范围超期'' AS [返回信息]'
	  /*SET @SQL = 
		'select 
		 '''' as [姓名], 
		 '''' as [学号], 
		 '''' as [部门名称],
		 '''' as [帐号],
		 '''' as [卡号], 
		 '''' as [身份类型],
		 '''' as [操作时间],
         '''' as [原余额], 
         '''' as [手续费],
         '''' as [现余额],       
         '''' as [操作员]'*/
	ELSE
	begin
	  SET @SQL =
         'select 
       b.fName as [姓名], 
       b.fEmployeeCode as [学号], 
       c.fDeptName as [部门名称],
       R.fAccount_id as [帐号],
       R.fCard_Number as [卡号], 
       f.fId_TypeName as [身份类型],
       R.fCons_Time as [操作时间],
       R.fOdd_Money as [原余额], 
       R.fsx_Money as [手续费],
       R.fX_Money as [现余额],               
       g.fOperName as [操作员]
	from ' + @sRet + CHAR(13) +
	' left join T_B_Employee b on R.fAccount_id = b.fAccountID                  
	  left join T_B_Dept c     on R.fDp_bh = c.fDeptCode 
	  left join T_B_Pos d      on R.fPos_id = d.fPosID
	  left join T_B_Station e  on R.fStation_Id = e.fStation_Id
	  left join T_B_ManType f on b.fId_TypeId = f.fId_TypeId
	  left join T_B_Manager g on R.fOper_ID = g. fOperID
	where fCons_State = 4 and
		  fSettleTime >= ''' + @strB + ''' and 
		  fSettleTime <= ''' + @strE + ''' '
	if @DeptCode <> ''
	  Set @SQL = @SQL + CHAR(13) + ' and  b.fDept like ''' + @DeptCode + '%'' '    
	if @Id_TypeId <> ''
      Set @SQL = @SQL + CHAR(13)+ ' and  b.fId_TypeId like ''' + @Id_TypeId + '%'' '
    Set @SQL = @SQL + CHAR(13)+ ' order by R.fAccount_id '	
	end
  --print @SQL
  exec sp_executesql @SQL
end
go


create procedure dbo.UP_Report_DZD_detail_HK 
       @Station     varchar(20),  -- 工作站；传值，工作站名称，只能传入一个工作站名称
       @BegDateTime varchar(20),  --开始查询日期
       @EndDateTime varchar(20),  --结束查询日
       @DeptCode   varchar(20),    -- 部门编号,为空查询所有部门
       @Id_TypeId   varchar(20)   --身份类型ID 
as
begin
	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'
	DECLARE @SQL nvarchar(4000),
	        @iRet int,
	        @sRet varchar(300)
	EXEC UP_R_CheckTime @strB, @strE, 1, @iRet output, @sRet output
	if @iRet = -9999 OR @sRet = ''
	  SET @SQL = 'SELECT ''查询表无效-查询表范围超期'' AS [返回信息]'
	  /*SET @SQL = 
		'select 
		 '''' as [姓名], 
		 '''' as [学号], 
		 '''' as [部门名称],
		 '''' as [帐号],
		 '''' as [卡号], 
		 '''' as [身份类型],
		 '''' as [操作时间],
         '''' as [原余额], 
         '''' as [手续费],
         '''' as [现余额],       
         '''' as [操作员]'*/
	ELSE
	begin
	  SET @SQL =
         'select 
       b.fName as [姓名], 
       b.fEmployeeCode as [学号], 
       c.fDeptName as [部门名称],
       R.fAccount_id as [帐号],
       R.fCard_Number as [卡号], 
       f.fId_TypeName as [身份类型],
       R.fCons_Time as [操作时间],
       R.fOdd_Money as [原余额], 
       R.fsx_Money as [手续费],
       R.fX_Money as [现余额],               
       g.fOperName as [操作员]
	from ' + @sRet + CHAR(13) +
	' left join T_B_Employee b on R.fAccount_id = b.fAccountID                  
	  left join T_B_Dept c     on R.fDp_bh = c.fDeptCode 
	  left join T_B_Pos d      on R.fPos_id = d.fPosID
	  left join T_B_Station e  on R.fStation_Id = e.fStation_Id
	  left join T_B_ManType f on b.fId_TypeId = f.fId_TypeId
	  left join T_B_Manager g on R.fOper_ID = g. fOperID
	where fCons_State = 9 and
		  fSettleTime >= ''' + @strB + ''' and 
		  fSettleTime <= ''' + @strE + ''' '
	if @DeptCode <> ''
	  Set @SQL = @SQL + CHAR(13) + ' and  b.fDept like ''' + @DeptCode + '%'' '    
	if @Id_TypeId <> ''
      Set @SQL = @SQL + CHAR(13)+ ' and  b.fId_TypeId like ''' + @Id_TypeId + '%'' '
    Set @SQL = @SQL + CHAR(13)+ ' order by R.fAccount_id '	
	end
  --print @SQL
  exec sp_executesql @SQL
end
go


create procedure dbo.UP_Report_DZD_detail_JG 
       @Station     varchar(20),  -- 工作站；传值，工作站名称，只能传入一个工作站名称
       @BegDateTime varchar(20),  --开始查询日期
       @EndDateTime varchar(20),  --结束查询日
       @DeptCode   varchar(20),    -- 部门编号,为空查询所有部门
       @Id_TypeId   varchar(20)   --身份类型ID 
as
begin
	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'
	DECLARE @SQL nvarchar(4000),
	        @iRet int,
	        @sRet varchar(300)
	EXEC UP_R_CheckTime @strB, @strE, 1, @iRet output, @sRet output
	if @iRet = -9999 OR @sRet = ''
	  SET @SQL = 'SELECT ''查询表无效-查询表范围超期'' AS [返回信息]'
	  /*SET @SQL = 
		'select 
		 '''' as [姓名], 
		 '''' as [学号], 
		 '''' as [部门名称],
		 '''' as [帐号],
		 '''' as [卡号], 
		 '''' as [身份类型],
		 '''' as [操作时间],
         '''' as [原余额], 
         '''' as [手续费],
         '''' as [现余额],       
         '''' as [操作员]'*/
	ELSE
	begin
	  SET @SQL =
         'select 
       b.fName as [姓名], 
       b.fEmployeeCode as [学号], 
       c.fDeptName as [部门名称],
       R.fAccount_id as [帐号],
       R.fCard_Number as [卡号], 
       f.fId_TypeName as [身份类型],
       R.fCons_Time as [操作时间],
       R.fOdd_Money as [原余额], 
       R.fsx_Money as [手续费],
       R.fX_Money as [现余额],               
       g.fOperName as [操作员]
	from ' + @sRet + CHAR(13) +
	' left join T_B_Employee b on R.fAccount_id = b.fAccountID                  
	  left join T_B_Dept c     on R.fDp_bh = c.fDeptCode 
	  left join T_B_Pos d      on R.fPos_id = d.fPosID
	  left join T_B_Station e  on R.fStation_Id = e.fStation_Id
	  left join T_B_ManType f on b.fId_TypeId = f.fId_TypeId
	  left join T_B_Manager g on R.fOper_ID = g. fOperID
	where fCons_State = 5 and
		  fSettleTime >= ''' + @strB + ''' and 
		  fSettleTime <= ''' + @strE + ''' '
	if @DeptCode <> ''
	  Set @SQL = @SQL + CHAR(13) + ' and  b.fDept like ''' + @DeptCode + '%'' '    
	if @Id_TypeId <> ''
      Set @SQL = @SQL + CHAR(13)+ ' and  b.fId_TypeId like ''' + @Id_TypeId + '%'' '
    Set @SQL = @SQL + CHAR(13)+ ' order by R.fAccount_id '	
	end
  --print @SQL
  exec sp_executesql @SQL
end
go


create procedure dbo.UP_Report_DZD_detail_KH 
       @Station     varchar(20),  -- 工作站；传值，工作站名称，只能传入一个工作站名称
       @BegDateTime varchar(20),  --开始查询日期
       @EndDateTime varchar(20),  --结束查询日
       @DeptCode   varchar(20),    -- 部门编号,为空查询所有部门
       @Id_TypeId   varchar(20)   --身份类型ID 
as
begin
	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'
	DECLARE @SQL nvarchar(4000),
	        @iRet int,
	        @sRet varchar(300)
	EXEC UP_R_CheckTime @strB, @strE, 1, @iRet output, @sRet output
	if @iRet = -9999 OR @sRet = ''
	  SET @SQL = 'SELECT ''查询表无效-查询表范围超期'' AS [返回信息]'
	  /*SET @SQL = 
		'select 
		 '''' as [姓名], 
		 '''' as [学号], 
		 '''' as [部门名称],
		 '''' as [帐号],
		 '''' as [卡号], 
		 '''' as [身份类型],
		 '''' as [操作时间],
         '''' as [写卡金额],
         '''' as [押金],
         '''' as [卡费],     
         '''' as [操作员]'*/
	ELSE
	begin
	  SET @SQL =
         'select 
       b.fName as [姓名], 
       b.fEmployeeCode as [学号], 
       c.fDeptName as [部门名称],
       R.fAccount_id as [帐号],
       R.fCard_Number as [卡号],
       f.fId_TypeName as [身份类型],
       R.fCons_Time as [操作时间],
       R.fX_Money as [写卡金额],
       R.fCons_Fare as [押金],
       R.fSx_Money as [卡费],
       g.fOperName as [操作员]
	from ' + @sRet + CHAR(13) +
	' left join T_B_Employee b on R.fAccount_id = b.fAccountID                  
	  left join T_B_Dept c     on R.fDp_bh = c.fDeptCode 
	  left join T_B_Pos d      on R.fPos_id = d.fPosID
	  left join T_B_Station e  on R.fStation_Id = e.fStation_Id
	  left join T_B_ManType f on b.fId_TypeId = f.fId_TypeId
	  left join T_B_Manager g on R.fOper_ID = g. fOperID
	where fCons_State = 6 and
		  fSettleTime >= ''' + @strB + ''' and 
		  fSettleTime <= ''' + @strE + ''' '
	if @DeptCode <> ''
	  Set @SQL = @SQL + CHAR(13) + ' and  b.fDept like ''' + @DeptCode + '%'' '    
	if @Id_TypeId <> ''
      Set @SQL = @SQL + CHAR(13)+ ' and  b.fId_TypeId like ''' + @Id_TypeId + '%'' '
    Set @SQL = @SQL + CHAR(13)+ ' order by R.fAccount_id '	
	end
  --print @SQL
  exec sp_executesql @SQL
end
go


create procedure dbo.UP_Report_EGS_EmpCurrRule 
  @Station     varchar(20),  -- 工作站；传值，工作站名称，只能传如一个工作站名称
  @strWhere varchar(1000),
  @POSID VARCHAR(12)='' 
as
DECLARE @strsql nvarchar(4000)
	DECLARE @TMPWHERE VARCHAR(500)
	set @TMPWHERE=''
	IF (@strWhere<>'')
	BEGIN 
		SET @TMPWHERE = ' WHERE ER.fAccountID IN (SELECT FAccountID FROM T_B_Employee WHERE '+@STRWHERE+') ' 
	END	
	IF (@POSID<>'')
	BEGIN 
		SET @TMPWHERE = @TMPWHERE+ ' and ER.fPosID= '+@POSID
	END		
	
	
	SET @strsql=  
	' select '+
	'		ER.fAccountID as [帐号],  '+ 
	'		fname as [姓名],  '+
	'		fDeptName as [部门], '+ 
	'		VE.fSerialNo as [物理卡号],  '+
	'		ER.fPosID as [机号],  '+
	'		fPosName as [设备名称],  '+
	'		case fDoor1Rule when 0 then ''×'' else ''√'' end  as [1门权限],  '+
	'		case fDoor2Rule when 0 then ''×'' else ''√'' end  as [2门权限],  '+
	'		case fDoor3Rule when 0 then ''×'' else ''√'' end  as [3门权限], '+
	'		case fDoor4Rule when 0 then ''×'' else ''√'' end  as [4门权限], '+
	'		fDeadLine as [授权到期日] '+
	' from ( '+

	' select a.fAccountID, fPosID,  '+
	'max(fDoor1Rule) as fDoor1Rule, max(fDoor2Rule) as fDoor2Rule, max(fDoor3Rule) as fDoor3Rule, max(fDoor4Rule) as fDoor4Rule, max(fDeadLine)as fDeadLine from  '+
	'( select fAccountID, fPosID, fEnable, fCtrlRuleID, fDoor1Rule, fDoor2Rule, fDoor3Rule, fDoor4Rule, fPass, fDeadLine , 1 as fRuleType   '+		
	' from T_E_EmpRule 	where (fDoor1Rule<>0)or(fDoor2Rule<>0)or(fDoor3Rule<>0)or(fDoor4Rule<>0)  '+
	' ) as a '+
	' group by fAccountID,fPosID '+	
	
	
	
	' ) ER inner join V_B_Employee VE on ER.fAccountID=VE.fAccountID and  VE.fCard_State=0	 '+  ------只取出正常的用户
	'    inner join V_B_EgsPos EP on ER.fPosID=EP.fPosID '+ @TMPWHERE +
	' order by er.fAccountID '    
exec sp_executesql @strsql
print  @strsql
go


create procedure dbo.UP_Report_EGS_EmpRuleHistory 
   @Station     varchar(20),  -- 工作站；传值，工作站名称，只能传如一个工作站名称
   @strWhere varchar(1000),
   @BeginDate varchar(10),
   @EndDate varchar(10) 
as
DECLARE @strsql nvarchar(4000)
	DECLARE @TMPWHERE VARCHAR(500)
	set @TMPWHERE=''
	IF (@strWhere<>'')
	BEGIN 
		SET @TMPWHERE = ' and eh.fAccountID IN (SELECT FAccountID FROM T_B_Employee WHERE '+@STRWHERE+') ' 
	END			
	SET @strsql=  
	'select  fGroupID as [组号], '+
	'		eh.fAccountID as [帐号], '+
	'		fname as [姓名], '+
	'		fDeptName as [部门], '+	
	--'		fCardNo as [卡号], '+
	'		eh.fPhysicalNo as [物理卡号], '+
	'		eh.fPosID as [机号], '+
	'		fPosName as [设备名称], '+
	'		case fDoor1Rule when 0 then ''×'' else ''√'' end  as [1门权限], '+
	'		case fDoor2Rule when 0 then ''×'' else ''√'' end  as [2门权限], '+
	'		case fDoor3Rule when 0 then ''×'' else ''√'' end  as [3门权限], '+
	'		case fDoor4Rule when 0 then ''×'' else ''√'' end  as [4门权限], '+
	'		fOperateTime as [操作时间], '+
	'		eh.fRemark as [备注] '+
	'From T_E_EmpRuleHistory EH inner join V_B_Employee VE on EH.fAccountID=VE.fAccountID '+
	'inner join V_B_EgsPos EP on EH.fPosID=EP.fPosID    '+
	'where   CONVERT(varchar(10), fOperateTime, 120) >= ''' + @BeginDate +  '''and ' +
			'CONVERT(varchar(10), fOperateTime, 120) <= ''' + @EndDate + '''' + @TMPWHERE;    
exec sp_executesql @strsql
--print @strsql
go


create procedure dbo.UP_Report_Egs_CardRecord 
    @strWhere varchar(1000),
  	@RecType int,
  	@BeginDate datetime,
  	@EndDate datetime,
  	@PosID varchar(5)='' 
  	as
BEGIN
	declare @b_Year varchar(4)
	declare @b_Month varchar(2)

	DECLARE @STRSQL nvarchar(4000),
			@iRet int,
			@sRet varchar(300)
	        
	EXEC UP_R_CheckTime @BeginDate, @EndDate, 3, @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 @b_Year=datename(yyyy,@BeginDate)
	set @b_Month=datename(mm,@BeginDate)
	set @BeginDate=Cast(@BeginDate as varchar(10))+' 00:00:00'
	set @EndDate=Cast(@EndDate as varchar(10))+' 23:59:59'

	declare @i int
	declare @MonthCount int
	declare @sql_table nvarchar(4000)
	declare @CurrDate datetime
	set @i=0
	set @MonthCount=datediff(mm,@BeginDate,@EndDate)

	declare @tmpWhere varchar(500)
	DECLARE @PosWhere nvarchar(100)
	declare @sType varchar(200)
	set @sType=''
	if @RecType<>0 
		set @sType= 'fRecType='+cast(@RecType as varchar(2))+' and '

	declare @TableName varchar(21)
	set @sql_table=''
	while (@i<=@MonthCount)
	begin
		set @CurrDate=dateadd(m,@i,@BeginDate)
		set @TableName='T_E_CardRecord_'+datename(yyyy,@CurrDate)+dbo.fn_FillZero(2,datename(mm,@CurrDate))

		set @tmpWhere=''
		if (@strWhere<>'')
		begin 
			set @tmpWhere = +@TableName+'.fAccountID in (SELECT fAccountID FROM T_B_Employee WHERE '+@StrWhere+') and ' 
		end

		SET @PosWhere=''
		IF (@PosID<>0)
		BEGIN 
			SET @PosWhere = 'and '+@TableName+'.fPosID = '+@PosID 
		END

	--	print @TableName
		if exists (select * from dbo.sysobjects where id = object_id(N'['+@TableName+']') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
		begin
			if @sql_table<>'' set @sql_table=@sql_table+CHAR(10)+' UNION '+CHAR(10)
			set @sql_table=@sql_table+
		'SELECT 
			  T_B_Employee.fName AS 姓名, 
			  '+@TableName+'.fAccountID AS 账号, 
			  '+@TableName+'.fCardNo AS 卡号, 
			  T_B_Pos.fPosName AS 门禁控制器, 
			  T_E_Door.fDoorName AS 门名称, 
			  T_E_RecType.fTypeName AS 记录类型,       
			  '+@TableName+'.fRecTime AS 打卡开门时间, 
			  '+@TableName+'.fReceiveTime AS 记录收取时间, 
			  '+@TableName+'.fCReaderID AS 读卡头ID
		FROM '+@TableName+' LEFT OUTER JOIN
			  T_E_RecType ON 
			  '+@TableName+'.fRecType = T_E_RecType.fTypeID LEFT OUTER JOIN
			  T_B_Employee ON 
			  '+@TableName+'.fAccountID = T_B_Employee.fAccountID LEFT OUTER JOIN
			  T_E_Door ON '+@TableName+'.fPosID = T_E_Door.fPosID AND 
			  '+@TableName+'.fDoorID = T_E_Door.fDoorID LEFT OUTER JOIN
			  T_B_Pos ON '+@TableName+'.fPosID = T_B_Pos.fPosID
		WHERE '+@sType+@tmpWhere+' (fRecTime>='''+convert(varchar(19),@begindate,20)+''' and fRecTime<='''+convert(varchar(19),@enddate,20)+''') '+@PosWhere
		end
		set @i=@i+1
	end
	exec sp_executesql @sql_Table
	--print @sql_Table
END
go


create procedure dbo.UP_Report_Egs_CardRecordN 
    @Station varchar(2),
  	@strWhere varchar(1000),
  	@RecType int,
  	@BeginDate datetime,
  	@EndDate datetime,
  	@PosID varchar(5)='' 
  	as
BEGIN
	DECLARE @STRSQL nvarchar(4000),
			@iRet int,
			@sRet varchar(300)
	        
	EXEC UP_R_CheckTime @BeginDate, @EndDate, 3, @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
	declare @b_Year varchar(4)
	declare @b_Month varchar(2)

	set @b_Year=datename(yyyy,@BeginDate)
	set @b_Month=datename(mm,@BeginDate)
	set @BeginDate=Cast(@BeginDate as varchar(10))+' 00:00:00'
	set @EndDate=Cast(@EndDate as varchar(10))+' 23:59:59'

	declare @i int
	declare @MonthCount int
	declare @sql_table nvarchar(4000)
	declare @CurrDate datetime
	set @i=0
	set @MonthCount=datediff(mm,@BeginDate,@EndDate)

	declare @tmpWhere varchar(500)
	DECLARE @PosWhere nvarchar(100)
	declare @sType varchar(200)
	set @sType=''
	if @RecType<>0 
		set @sType= 'fRecType='+cast(@RecType as varchar(2))+' and '

	declare @TableName varchar(21)
	set @sql_table=''
	while (@i<=@MonthCount)
	begin
		set @CurrDate=dateadd(m,@i,@BeginDate)
		set @TableName='T_E_CardRecord_'+datename(yyyy,@CurrDate)+dbo.fn_FillZero(2,datename(mm,@CurrDate))

		set @tmpWhere=''
		if (@strWhere<>'')
		begin 
			set @tmpWhere = +@TableName+'.fAccountID in (SELECT fAccountID FROM T_B_Employee WHERE '+@StrWhere+') and ' 
		end

		SET @PosWhere=''
		IF (@PosID<>0)
		BEGIN 
			SET @PosWhere = 'and '+@TableName+'.fPosID = '+@PosID 
		END

	--	print @TableName
		if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].['+@TableName+']') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
		begin
			if @sql_table<>'' set @sql_table=@sql_table+CHAR(10)+' UNION '+CHAR(10)
			set @sql_table=@sql_table+
		'SELECT 
			  T_B_Employee.fName AS 姓名, 
			  '+@TableName+'.fAccountID AS 账号, 
			  '+@TableName+'.fCardNo AS 卡号, 
			  T_B_Pos.fPosName AS 门禁控制器, 
			  T_E_Door.fDoorName AS 门名称, 
			  T_E_RecType.fTypeName AS 记录类型,       
			  '+@TableName+'.fRecTime AS 打卡开门时间, 
			  '+@TableName+'.fReceiveTime AS 记录收取时间, 
			  '+@TableName+'.fCReaderID AS 读卡头ID
		FROM '+@TableName+' LEFT OUTER JOIN
			  T_E_RecType ON 
			  '+@TableName+'.fRecType = T_E_RecType.fTypeID LEFT OUTER JOIN
			  T_B_Employee ON 
			  '+@TableName+'.fAccountID = T_B_Employee.fAccountID LEFT OUTER JOIN
			  T_E_Door ON '+@TableName+'.fPosID = T_E_Door.fPosID AND 
			  '+@TableName+'.fDoorID = T_E_Door.fDoorID LEFT OUTER JOIN
			  T_B_Pos ON '+@TableName+'.fPosID = T_B_Pos.fPosID
		WHERE '+@sType+@tmpWhere+' (fRecTime>='''+convert(varchar(19),@begindate,20)+''' and fRecTime<='''+convert(varchar(19),@enddate,20)+''') '+@PosWhere
		end
		set @i=@i+1
	end
	exec sp_executesql @sql_Table
	--print @sql_Table
END
go


create procedure dbo.UP_Report_Egs_ErrorRecord 
    @Station varchar(2),
  	@ErrorCode int,
  	@BeginDate datetime,
  	@EndDate datetime 
  	as
IF @ErrorCode=0
	SELECT * FROM V_E_ErrorRec WHERE 发生时间>=@BeginDate and 发生时间<=@EndDate
ELSE
	SELECT * FROM V_E_ErrorRec WHERE 错误代码=@ErrorCode and (发生时间>=@BeginDate and 发生时间<=@EndDate)
go

create procedure dbo.UP_Report_Total_AccountDeposit 
       @Station     varchar(20),  -- 工作站；传值，工作站名称，只能传入一个工作站名称
       @BegDateTime varchar(20),  --开始查询日期
       @EndDateTime varchar(20),  --结束查询日
       @DeptCode   varchar(20)    -- 部门编号,为空查询所有部门 
as
BEGIN
	declare @STRSQL varchar(8000),
			@iRet int,
			@sRet varchar(300),
			@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'
	EXEC UP_R_CheckTime @strB, @strE, 1, @iRet output, @sRet output 
	if @iRet = -9999 OR @sRet = ''
	begin
		SET @STRSQL = 'SELECT ''查询表无效-查询表范围超期'' AS [返回信息]'
	end
	ELSE
	begin
		SET @STRSQL =
		'select R.fAccount_id as 帐号, R.fCard_Number as 卡号, E.fName as 姓名, E.fDept as 部门编号, D.fDeptName as 部门名称, 
		SUM(isnull(R.svcount,0.00)) as 存款次数, 
		SUM(isnull(R.svmoney,0.00)) as 存款金额, 
		SUM(isnull(R.tkcount,0.00)) as 取款次数,
		SUM(isnull(R.tkmoney,0.00)) as 取款金额,
		SUM(isnull(R.svmoney,0.00)) - SUM(isnull(R.tkmoney,0.00))  as 合计
		from 
		( select R.fAccount_id,R.fCard_Number,
		  SUM(case when R.fCons_State in(1,28) then 1 else 0 end) as svcount,  --存款次数
		  SUM(case when R.fCons_State in(1,28) then R.fCons_Fare else 0.00 end) as svmoney,  --存款金额
		  SUM(case when R.fCons_State in(2,30) then 1 else 0 end) as tkcount,  --取款次数
		  SUM(case when R.fCons_State in(2,30) then R.fCons_Fare else 0.00 end) as tkmoney      --取款金额
			from ' + CHAR(13) +
			@sRet + CHAR(13) +
		'	where R.fCons_State in (1,2,28,30)
				  and R.fSettleTime >= ''' + @strB + '''
	  			  and R.fSettleTime <= ''' + @strE + '''
			group by R.fAccount_id,R.fCard_Number
		) R 
		 Left join T_B_Employee E on E.fAccountID = R.fAccount_id 
		 Left join T_B_Dept D on E.fDept = D.fDeptCode
		where  (E.fDept like ''' + @DeptCode + '%'' )
		group by R.fAccount_id, R.fCard_Number, fName, fDept, fDeptName'
	end
  --print @STRSQL   
  exec(@STRSQL)
END
go


create procedure dbo.UP_Report_Yzf_Count 
  @Station     VARCHAR(20),  -- 工作站；  
  @BegDateTime VARCHAR(20),  --开始查询日期  
  @EndDateTime VARCHAR(20),  --结束查询日  
  @DeptCode VARCHAR(40)='',--部门  
  @AccountWhere VARCHAR(200)='' --查询人员的条件 
  as
DECLARE  
  @strB VARCHAR(30), --开始查询时间  
  @strE VARCHAR(30), --结束查询时间  
  @STRSQL VARCHAR(2000),  
  @AccWhere VARCHAR(500) --查询条件  
    
 SET @strB = CONVERT(VARCHAR(20), @BegDateTime, 23) + ' 00:00:00'  
 SET @strE = CONVERT(VARCHAR(20), @EndDateTime, 23) + ' 23:59:59'  
   
 IF @AccountWhere <> ''  
  SET @AccWhere = ' Where ' + @AccountWhere  
 ELSE  
  SET @AccWhere = ' Where 1=1 '  
   
 IF @DeptCode <> ''  
       SET @AccWhere = @AccWhere + ' and b.fDept like ''' +@DeptCode + '%'' '  
    
         
 SET @STRSQL=' select 
 
 a.orderId 订单号,
a.phoneNumber 手机号,
a.iccid 学号,
a.NAME 姓名,
a.amount/100 转账金额,
a.orderDate 订单时间,
(case when a.flag=1 then ''已对账'' else''未对账'' end) 对账标示,
a.dealTime 对账时间
 from tb_yzf_record a left join t_b_employee b on a.iccid =b.fEmployeeCode'+@AccWhere 
 print @STRSQL
 EXEC(@STRSQL)
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


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


create procedure dbo.UP_UpdateKEY 
    @KeyValue varchar(100),
  	@KeyType int 
  	as
UPDATE T_B_Keys SET fPassword=@KeyValue WHERE fPswType=@KeyType
	if @@rowcount = 0
		INSERT INTO T_B_Keys VALUES(@KeyType, @KeyValue)
go


create procedure dbo.Up_Report_ATD_EvectionReclist 
  @mode int,
  @fNoteCode varchar(18),
  @FaccountID varchar(18),
  @fDestination varchar(4),
  @fTimeBegin datetime,
  @fTimeEnd datetime,
  @fAllday bit,
  @fApprover varchar(8),
  @fDays tinyint,
  @fMinutes smallint,
  @fEvectionReason varchar(100),
  @keyid int 
as
declare @LevDAY int
 declare @fkeyID int 
 declare @i int
 declare @month int
 declare @day int
 declare @SQL VARCHAR(2000)
 declare @Newdate datetime
 if @mode=0  -----------0表示插入数据
 begin
    insert into T_B_EvectionRec(fNoteCode,fAccountID,fDestination,fTimeBegin,fTimeEnd,fAllDay,fApprover,fDays,fMinutes,fEvectionReason)
    values(@fNoteCode,@fAccountID,@fDestination,@fTimeBegin,@fTimeEnd,@fAllDay,@fApprover,@fDays,@fMinutes,@fEvectionReason)
 end
 else if @mode=1 ----1表示修改
 begin
  update T_B_EvectionRec set  
         fNoteCode=@fNoteCode
         ,fDestination=@fDestination 
        , fTimeBegin=@fTimeBegin
        ,fTimeEnd=@fTimeEnd
        ,fAllDay=@fAllDay
        ,fDays=@fDays
        ,fMinutes=@fMinutes
        ,fApprover=@fApprover
        ,fEvectionReason=@fEvectionReason
   where fAccountID=@fAccountID and fKeyID=@KeyID
   delete T_B_EvectionReclist where fkeyID=@keyid
 end
 
select @fkeyID=fkeyid, @fNoteCode=fNoteCode,@FaccountID=fAccountID,@fDestination=fDestination from T_B_EvectionRec
       where fAccountID=@fAccountID and fNoteCode=@fNoteCode and @fEvectionReason=fEvectionReason and fTimeBegin=@fTimeBegin
       and fTimeEnd=@fTimeEnd
       
       
SET @LevDAY=DATEDIFF(DAY,@fTimeBegin,@fTimeEnd)
set @Month=MONTH(@fTimeBegin)
set @i=0 
if @LevDAY<=0 
begin
   insert into T_B_EvectionReclist(fkeyID,fNoteCode,fDestination,fAccountID,fTimeBegin,fTimeEnd,fAllday,fapprover,fdays,fMinutes,fEvectionReason) 
   values(@fkeyID,@fNoteCode,@fDestination,@FaccountID,CONVERT(varchar(100), @fTimeBegin, 9),
    CONVERT(varchar(100), @fTimeEnd, 9),@fAllday,@fapprover,@fdays,@fMinutes,@fEvectionReason)
 end 
else  --为跨多天请假
begin
  while @i<=@LevDAY 
  begin
   if @i = 0  --第一天，只取班次结束时间
   begin
     set @Newdate=@fTimeBegin
     set @Day=cast(DAY(@Newdate) as varchar(10))   
	 set  @SQL=
	   ' declare @fWorkTimeID varchar(10)' + CHAR(13) 
	  +' declare @fOffDuty varchar(10)' + CHAR(13) 
	  +' declare @fOffDuty1 varchar(10)' + CHAR(13) 
	  +' declare @fOffDuty2 varchar(10)' + CHAR(13) 
	  +' declare @fOffDuty3 varchar(10)' + CHAR(13) 
	  +' declare @fOffDuty4 varchar(10)' + CHAR(13) 
	  +' declare @fOffDuty5 varchar(10)' + CHAR(13) 
	  +' declare @fOffDuty6 varchar(10)' + CHAR(13)
	  +' select @fWorkTimeID = fDay'+cast(@Day as varchar(10))+' from T_A_WTArrange WHERE   Fmonth='+cast(month(@Newdate) as varchar(10))+  CHAR(13) +
	  +' and fYear='+CAST(YEAR(@Newdate) as varchar(10))+' and faccountid='''+@FaccountID+''''  + CHAR(13) +
	  +' select @fOffDuty1 = fOffDuty1,@fOffDuty2 = fOffDuty2,@fOffDuty3 = fOffDuty3,@fOffDuty4 = fOffDuty4,@fOffDuty5 = fOffDuty5,@fOffDuty6 = fOffDuty6 from T_A_WorkTime where fWorkTimeCode = @fWorkTimeID '  + CHAR(13) +   
	  +' if @fOffDuty6 <> '''' ' + CHAR(13)
	  +'   set @fOffDuty = @fOffDuty6 ' + CHAR(13)
	  +' else if @fOffDuty5 <> '''' ' + CHAR(13)
	  +'   set @fOffDuty = @fOffDuty5 ' + CHAR(13)
	  +' else if @fOffDuty4 <> '''' ' + CHAR(13)
	  +'   set @fOffDuty = @fOffDuty4 ' + CHAR(13)
	  +' else if @fOffDuty3 <> '''' ' + CHAR(13)
	  +'   set @fOffDuty = @fOffDuty3 ' + CHAR(13)
	  +' else if @fOffDuty2 <> '''' ' + CHAR(13)
	  +'   set @fOffDuty = @fOffDuty2 ' + CHAR(13)	  	  	  
	   +' else set @fOffDuty = @fOffDuty1 ' + CHAR(13)
	  +' insert into T_B_EvectionReclist(fkeyID,fNoteCode,fDestination,FaccountID,fTimeBegin,fTimeEnd,fAllday,fapprover,fdays,fMinutes,fEvectionReason) 
		 values('+cast(@fkeyID as varchar(10))+','''+
		         @fNoteCode+''','''+
		         @fDestination+''','''+
		         @FaccountID+''','''+ 
		         CONVERT(varchar(50), @Newdate, 9)+''','''+ 
		         cast(DatePart(yyyy,@Newdate) as varchar(4)) +'-' + cast(DatePart(mm,@Newdate) as varchar(2)) +'-' + cast(DatePart(dd,@Newdate) as varchar(2)) + ' '' + @fOffDuty + '':00'','+
		         --CONVERT(varchar(50),@Newdate,110)+''','+
		         cast(@fAllday as varchar(5))+','''+
		         @fapprover+''' ,'''+
		         cast(@fdays as varchar(10))+''' ,'''+
		         cast(@fMinutes as varchar(10))+''' ,'''+
		         @fEvectionReason+''' 
		  ) '	  
   end
   else if @i = @LevDAY --最后一天，只取班次开始时间
   begin
     set @Newdate=@fTimeEnd
     set @Day=cast(DAY(@Newdate) as varchar(10))    
     set  @SQL=
	   ' declare @fWorkTimeID varchar(10)' + CHAR(13) 
	  +' declare @fOnDuty varchar(10)' + CHAR(13) 
	  +' select @fWorkTimeID = fDay'+cast(@Day as varchar(10))+' from T_A_WTArrange WHERE   Fmonth='+cast(month(@Newdate) as varchar(10))+  CHAR(13) +
	  +' and fYear='+CAST(YEAR(@Newdate) as varchar(10))+' and faccountid='''+@FaccountID+''''  + CHAR(13) +
	  +' select @fOnDuty  = fOnDuty1 from  T_A_WorkTime where fWorkTimeCode = @fWorkTimeID '  + CHAR(13) +   
	  +' insert into T_B_EvectionReclist(fkeyID,fNoteCode,fDestination,FaccountID,fTimeBegin,fTimeEnd,fAllday,fapprover,fdays,fMinutes,fEvectionReason) 
		 values('+cast(@fkeyID as varchar(10))+','''+
		         @fNoteCode+''','''+
		         @fDestination+''','''+
		         @FaccountID+''','''+ 
		         cast(DatePart(yyyy,@Newdate) as varchar(4)) +'-' + cast(DatePart(mm,@Newdate) as varchar(2)) +'-' + cast(DatePart(dd,@Newdate) as varchar(2)) + ' '' + @fOnDuty + '':00'','''+
		         CONVERT(varchar(50), @Newdate, 9)+''','+ 
		         --CONVERT(varchar(50),@Newdate,110)+''','+
		         cast(@fAllday as varchar(5))+','''+
		         @fapprover+''' ,'''+
		         cast(@fdays as varchar(10))+''' ,'''+
		         cast(@fMinutes as varchar(10))+''' ,'''+
		         @fEvectionReason+''' 
		  ) '
   end
   else   --中间天数，需要取得当天班次的开始和结束时间
   begin
     set @Newdate=@fTimeBegin+@i
     set @Day=cast(DAY(@Newdate) as varchar(10))  
	 set  @SQL=
	   ' declare @fWorkTimeID varchar(10)' + CHAR(13) 
      +' declare @fOnDuty varchar(10)' + CHAR(13) 	   
	  +' declare @fOffDuty varchar(10)' + CHAR(13) 
	  +' declare @fOffDuty1 varchar(10)' + CHAR(13) 
	  +' declare @fOffDuty2 varchar(10)' + CHAR(13) 
	  +' declare @fOffDuty3 varchar(10)' + CHAR(13) 
	  +' declare @fOffDuty4 varchar(10)' + CHAR(13) 
	  +' declare @fOffDuty5 varchar(10)' + CHAR(13) 
	  +' declare @fOffDuty6 varchar(10)' + CHAR(13)
	  +' select @fWorkTimeID = fDay'+cast(@Day as varchar(10))+' from T_A_WTArrange WHERE   Fmonth='+cast(month(@Newdate) as varchar(10))+  CHAR(13) +
	  +' and fYear='+CAST(YEAR(@Newdate) as varchar(10))+' and faccountid='''+@FaccountID+''''  + CHAR(13) +
	  +' select @fOnDuty = fOnDuty1, @fOffDuty1 = fOffDuty1,@fOffDuty2 = fOffDuty2,@fOffDuty3 = fOffDuty3,@fOffDuty4 = fOffDuty4,@fOffDuty5 = fOffDuty5,@fOffDuty6 = fOffDuty6 from T_A_WorkTime where fWorkTimeCode = @fWorkTimeID '  + CHAR(13) +   
	  +' if @fOffDuty6 <> '''' ' + CHAR(13)
	  +'   set @fOffDuty = @fOffDuty6 ' + CHAR(13)
	  +' else if @fOffDuty5 <> '''' ' + CHAR(13)
	  +'   set @fOffDuty = @fOffDuty5 ' + CHAR(13)
	  +' else if @fOffDuty4 <> '''' ' + CHAR(13)
	  +'   set @fOffDuty = @fOffDuty4 ' + CHAR(13)
	  +' else if @fOffDuty3 <> '''' ' + CHAR(13)
	  +'   set @fOffDuty = @fOffDuty3 ' + CHAR(13)
	  +' else if @fOffDuty2 <> '''' ' + CHAR(13)
	  +'   set @fOffDuty = @fOffDuty2 ' + CHAR(13)	  	  	  
	   +' else set @fOffDuty = @fOffDuty1 ' + CHAR(13)
	  +' insert into T_B_EvectionReclist(fkeyID,fNoteCode,fDestination,FaccountID,fTimeBegin,fTimeEnd,fAllday,fapprover,fdays,fMinutes,fEvectionReason) 
		 values('+cast(@fkeyID as varchar(10))+','''+
		         @fNoteCode+''','''+
		         @fDestination+''','''+
		         @FaccountID+''','''+ 
		         cast(DatePart(yyyy,@Newdate) as varchar(4)) +'-' + cast(DatePart(mm,@Newdate) as varchar(2)) +'-' + cast(DatePart(dd,@Newdate) as varchar(2)) + ' '' + @fOnDuty + '':00'','''+
		         cast(DatePart(yyyy,@Newdate) as varchar(4)) +'-' + cast(DatePart(mm,@Newdate) as varchar(2)) +'-' + cast(DatePart(dd,@Newdate) as varchar(2)) + ' '' + @fOffDuty + '':00'','+
		         --CONVERT(varchar(50),@Newdate,110)+''','+
		         cast(@fAllday as varchar(5))+','''+
		         @fapprover+''' ,'''+
		         cast(@fdays as varchar(10))+''' ,'''+
		         cast(@fMinutes as varchar(10))+''' ,'''+
		         @fEvectionReason+''' 
		  ) '	     
   end
   print @sql
   exec (@sql)
   set @SQL=''
   set @i = @i + 1
   end
 end
go


create procedure dbo.Up_Report_ATD_LeaveReclist 
  @mode int,
  @fNoteCode varchar(18),
  @FaccountID varchar(18),
  @fLeaveType varchar(4),
  @fTimeBegin datetime,
  @fTimeEnd datetime,
  @fAllday bit,
  @fApprover varchar(8),
  @fDays tinyint,
  @fMinutes smallint,
  @fLeaveReason varchar(100),
  @keyid int 
as
declare @LevDAY int
 declare @fkeyID int 
 declare @i int
 declare @month int
 declare @day int
 declare @SQL VARCHAR(2000)
 declare @Newdate datetime
 if @mode=0 
 begin
    insert into T_B_LeaveRec(fNoteCode,fAccountID,fLeaveType,fTimeBegin,fTimeEnd,fAllDay,fApprover,fDays,fMinutes,fLeaveReason)
    values(@fNoteCode,@fAccountID,@fLeaveType,@fTimeBegin,@fTimeEnd,@fAllDay,@fApprover,@fDays,@fMinutes,@fLeaveReason)
 end
 else if @mode=1 
 begin
  update T_B_LeaveRec set  
        fNoteCode=@fNoteCode
         ,fLeaveType=@fLeaveType 
        , fTimeBegin=@fTimeBegin
        ,fTimeEnd=@fTimeEnd
        ,fAllDay=@fAllDay
        ,fDays=@fDays
        ,fMinutes=@fMinutes
        ,fApprover=@fApprover
        ,fLeaveReason=@fLeaveReason
   where fAccountID=@fAccountID and fKeyID=@KeyID
   delete T_B_LeaveReclist where fkeyID=@keyid
 end
 
select @fkeyID=fkeyid, @fNoteCode=fNoteCode,@FaccountID=fAccountID,@fLeaveType=fLeaveType from T_B_LeaveRec
       where fAccountID=@fAccountID and fNoteCode=@fNoteCode and fLeaveType=@fLeaveType and fTimeBegin=@fTimeBegin
       and fTimeEnd=@fTimeEnd
SET @LevDAY=DATEDIFF(DAY,@fTimeBegin,@fTimeEnd)
set @Month=MONTH(@fTimeBegin)
set @i=0 
if @LevDAY<=0 
begin
   insert into T_B_LeaveReclist(fkeyID,fNoteCode,fleavetype,fAccountID,fTimeBegin,fTimeEnd,fAllday,fapprover,fdays,fMinutes,fleaveReason) 
   values(@fkeyID,@fNoteCode,@fleavetype,@FaccountID,CONVERT(varchar(100), @fTimeBegin, 9),
    CONVERT(varchar(100), @fTimeEnd, 9),@fAllday,@fapprover,@fdays,@fMinutes,@fleaveReason)
 end 
else  --为跨多天请假
begin
  while @i<=@LevDAY 
  begin
   if @i = 0  --第一天，只取班次结束时间
   begin
     set @Newdate=@fTimeBegin
     set @Day=cast(DAY(@Newdate) as varchar(10))   
	 set  @SQL=
	   ' declare @fWorkTimeID varchar(10)' + CHAR(13) 
	  +' declare @fOffDuty varchar(10)' + CHAR(13) 
	  +' declare @fOffDuty1 varchar(10)' + CHAR(13) 
	  +' declare @fOffDuty2 varchar(10)' + CHAR(13) 
	  +' declare @fOffDuty3 varchar(10)' + CHAR(13) 
	  +' declare @fOffDuty4 varchar(10)' + CHAR(13) 
	  +' declare @fOffDuty5 varchar(10)' + CHAR(13) 
	  +' declare @fOffDuty6 varchar(10)' + CHAR(13)
	  +' select @fWorkTimeID = fDay'+cast(@Day as varchar(10))+' from T_A_WTArrange WHERE   Fmonth='+cast(month(@Newdate) as varchar(10))+  CHAR(13) +
	  +' and fYear='+CAST(YEAR(@Newdate) as varchar(10))+' and faccountid='''+@FaccountID+''''  + CHAR(13) +
	  +' select @fOffDuty1 = fOffDuty1,@fOffDuty2 = fOffDuty2,@fOffDuty3 = fOffDuty3,@fOffDuty4 = fOffDuty4,@fOffDuty5 = fOffDuty5,@fOffDuty6 = fOffDuty6 from T_A_WorkTime where fWorkTimeCode = @fWorkTimeID '  + CHAR(13) +   
	  +' if @fOffDuty6 <> '''' ' + CHAR(13)
	  +'   set @fOffDuty = @fOffDuty6 ' + CHAR(13)
	  +' else if @fOffDuty5 <> '''' ' + CHAR(13)
	  +'   set @fOffDuty = @fOffDuty5 ' + CHAR(13)
	  +' else if @fOffDuty4 <> '''' ' + CHAR(13)
	  +'   set @fOffDuty = @fOffDuty4 ' + CHAR(13)
	  +' else if @fOffDuty3 <> '''' ' + CHAR(13)
	  +'   set @fOffDuty = @fOffDuty3 ' + CHAR(13)
	  +' else if @fOffDuty2 <> '''' ' + CHAR(13)
	  +'   set @fOffDuty = @fOffDuty2 ' + CHAR(13)	  	  	  
	   +' else set @fOffDuty = @fOffDuty1 ' + CHAR(13)
	  +' insert into T_B_LeaveReclist(fkeyID,fNoteCode,fleavetype,FaccountID,fTimeBegin,fTimeEnd,fAllday,fapprover,fdays,fMinutes,fleaveReason) 
		 values('+cast(@fkeyID as varchar(10))+','''+
		         @fNoteCode+''','''+
		         @fleavetype+''','''+
		         @FaccountID+''','''+ 
		         CONVERT(varchar(50), @Newdate, 9)+''','''+ 
		         cast(DatePart(yyyy,@Newdate) as varchar(4)) +'-' + cast(DatePart(mm,@Newdate) as varchar(2)) +'-' + cast(DatePart(dd,@Newdate) as varchar(2)) + ' '' + @fOffDuty + '':00'','+
		         --CONVERT(varchar(50),@Newdate,110)+''','+
		         cast(@fAllday as varchar(5))+','''+
		         @fapprover+''' ,'''+
		         cast(@fdays as varchar(10))+''' ,'''+
		         cast(@fMinutes as varchar(10))+''' ,'''+
		         @fleaveReason+''' 
		  ) '	  
   end
   else if @i = @LevDAY --最后一天，只取班次开始时间
   begin
     set @Newdate=@fTimeEnd
     set @Day=cast(DAY(@Newdate) as varchar(10))    
     set  @SQL=
	   ' declare @fWorkTimeID varchar(10)' + CHAR(13) 
	  +' declare @fOnDuty varchar(10)' + CHAR(13) 
	  +' select @fWorkTimeID = fDay'+cast(@Day as varchar(10))+' from T_A_WTArrange WHERE   Fmonth='+cast(month(@Newdate) as varchar(10))+  CHAR(13) +
	  +' and fYear='+CAST(YEAR(@Newdate) as varchar(10))+' and faccountid='''+@FaccountID+''''  + CHAR(13) +
	  +' select @fOnDuty  = fOnDuty1 from  T_A_WorkTime where fWorkTimeCode = @fWorkTimeID '  + CHAR(13) +   
	  +' insert into T_B_LeaveReclist(fkeyID,fNoteCode,fleavetype,FaccountID,fTimeBegin,fTimeEnd,fAllday,fapprover,fdays,fMinutes,fleaveReason) 
		 values('+cast(@fkeyID as varchar(10))+','''+
		         @fNoteCode+''','''+
		         @fleavetype+''','''+
		         @FaccountID+''','''+ 
		         cast(DatePart(yyyy,@Newdate) as varchar(4)) +'-' + cast(DatePart(mm,@Newdate) as varchar(2)) +'-' + cast(DatePart(dd,@Newdate) as varchar(2)) + ' '' + @fOnDuty + '':00'','''+
		         CONVERT(varchar(50), @Newdate, 9)+''','+ 
		         --CONVERT(varchar(50),@Newdate,110)+''','+
		         cast(@fAllday as varchar(5))+','''+
		         @fapprover+''' ,'''+
		         cast(@fdays as varchar(10))+''' ,'''+
		         cast(@fMinutes as varchar(10))+''' ,'''+
		         @fleaveReason+''' 
		  ) '
   end
   else   --中间天数，需要取得当天班次的开始和结束时间
   begin
     set @Newdate=@fTimeBegin+@i
     set @Day=cast(DAY(@Newdate) as varchar(10))  
	 set  @SQL=
	   ' declare @fWorkTimeID varchar(10)' + CHAR(13) 
      +' declare @fOnDuty varchar(10)' + CHAR(13) 	   
	  +' declare @fOffDuty varchar(10)' + CHAR(13) 
	  +' declare @fOffDuty1 varchar(10)' + CHAR(13) 
	  +' declare @fOffDuty2 varchar(10)' + CHAR(13) 
	  +' declare @fOffDuty3 varchar(10)' + CHAR(13) 
	  +' declare @fOffDuty4 varchar(10)' + CHAR(13) 
	  +' declare @fOffDuty5 varchar(10)' + CHAR(13) 
	  +' declare @fOffDuty6 varchar(10)' + CHAR(13)
	  +' select @fWorkTimeID = fDay'+cast(@Day as varchar(10))+' from T_A_WTArrange WHERE   Fmonth='+cast(month(@Newdate) as varchar(10))+  CHAR(13) +
	  +' and fYear='+CAST(YEAR(@Newdate) as varchar(10))+' and faccountid='''+@FaccountID+''''  + CHAR(13) +
	  +' select @fOnDuty = fOnDuty1, @fOffDuty1 = fOffDuty1,@fOffDuty2 = fOffDuty2,@fOffDuty3 = fOffDuty3,@fOffDuty4 = fOffDuty4,@fOffDuty5 = fOffDuty5,@fOffDuty6 = fOffDuty6 from T_A_WorkTime where fWorkTimeCode = @fWorkTimeID '  + CHAR(13) +   
	  +' if @fOffDuty6 <> '''' ' + CHAR(13)
	  +'   set @fOffDuty = @fOffDuty6 ' + CHAR(13)
	  +' else if @fOffDuty5 <> '''' ' + CHAR(13)
	  +'   set @fOffDuty = @fOffDuty5 ' + CHAR(13)
	  +' else if @fOffDuty4 <> '''' ' + CHAR(13)
	  +'   set @fOffDuty = @fOffDuty4 ' + CHAR(13)
	  +' else if @fOffDuty3 <> '''' ' + CHAR(13)
	  +'   set @fOffDuty = @fOffDuty3 ' + CHAR(13)
	  +' else if @fOffDuty2 <> '''' ' + CHAR(13)
	  +'   set @fOffDuty = @fOffDuty2 ' + CHAR(13)	  	  	  
	   +' else set @fOffDuty = @fOffDuty1 ' + CHAR(13)
	  +' insert into T_B_LeaveReclist(fkeyID,fNoteCode,fleavetype,FaccountID,fTimeBegin,fTimeEnd,fAllday,fapprover,fdays,fMinutes,fleaveReason) 
		 values('+cast(@fkeyID as varchar(10))+','''+
		         @fNoteCode+''','''+
		         @fleavetype+''','''+
		         @FaccountID+''','''+ 
		         cast(DatePart(yyyy,@Newdate) as varchar(4)) +'-' + cast(DatePart(mm,@Newdate) as varchar(2)) +'-' + cast(DatePart(dd,@Newdate) as varchar(2)) + ' '' + @fOnDuty + '':00'','''+
		         cast(DatePart(yyyy,@Newdate) as varchar(4)) +'-' + cast(DatePart(mm,@Newdate) as varchar(2)) +'-' + cast(DatePart(dd,@Newdate) as varchar(2)) + ' '' + @fOffDuty + '':00'','+
		         --CONVERT(varchar(50),@Newdate,110)+''','+
		         cast(@fAllday as varchar(5))+','''+
		         @fapprover+''' ,'''+
		         cast(@fdays as varchar(10))+''' ,'''+
		         cast(@fMinutes as varchar(10))+''' ,'''+
		         @fleaveReason+''' 
		  ) '	     
   end
   --print @sql
   exec (@sql)
   set @SQL=''
   set @i = @i + 1
   end
 end
go

CREATE procedure [dbo].[UP_Report_Cns_Total_CashSource] 
      @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 @Where varchar(2000) 
	declare @Where1 varchar(2000) 
	DECLARE @strB varchar(30),  
			@strE varchar(30) 
	DECLARE @iRet int,
	        @sRet varchar(4000)		 
	SET @strB = CONVERT(varchar(20), @BegDateTime, 23) + ' 00:00:00.000'  
	SET @strE = CONVERT(varchar(20), @EndDateTime, 23) + ' 23:59:59.999'  
	SET @iRet = -9999
	SET @sRet = ''
	EXEC UP_R_CheckTime @strB, @strE, 1, @iRet output, @sRet output    
	if @iRet = -9999 OR @sRet = ''    
	begin    
		if @iRet = -9999    
		  SET @SQLSTR = 'SELECT ''查询表无效-查询表范围超期'' AS [返回信息]'    
		else if @sRet = ''    
		  SET @SQLSTR = 'SELECT ''查询表无效-查询范围内没有流水产生'' AS [返回信息]'    
		else    
		  SET @SQLSTR = 'SELECT ''查询表无效-无法确定的原因'' AS [返回信息]'      
		--print @SQLSTR       
		exec(@SQLSTR)    
		Return    
	end     
	
	--print @strB  
	--print @strE  
	SET @Where = ''
	if(@STATIONID <> '')  
	  set @Where = + @Where + ' and fSiteID = ''' + @STATIONID +''' '  
	SET @Where1 = ''  
    if(@oper_id <> '')  
      set @Where1 = ' where ' + @oper_id 
	set @sqlstr =   
		'  select M.fOperName + ''['' + CAST(A.fOperID as varchar(10)) + '']'' as [操作员]
				 , PC.fPurseName + ''['' + CAST(A.fPurseID as varchar(10)) + '']'' as [钱包]
				 , A.fDate as [日期]
				 , A.fAmount_Save_S0 as [存款|现金|金额], A.fCount_Save_S0 as [存款|现金|次数]
				 , A.fAmount_Save_S1 as [存款|支付宝|金额], A.fCount_Save_S1 as [存款|支付宝|次数]
				 , A.fAmount_Save_S2 as [存款|微信|金额], A.fCount_Save_S2 as [存款|微信|次数]
				 , A.fAmount_Save_S3 as [存款|银联|金额], A.fCount_Save_S3 as [存款|银联|次数]
				 , A.fAmount_Save_S0 + A.fAmount_Save_S1 + A.fAmount_Save_S2 + A.fAmount_Save_S3 as [存款小计|金额]
				 , A.fCount_Save_S0 + A.fCount_Save_S1 + A.fCount_Save_S2 + A.fCount_Save_S3 as [存款小计|次数]
				 , A.fAmount_Take_S0 as [取款|现金|金额], A.fCount_Take_S0 as [取款|现金|次数]
				 , A.fAmount_Take_S1 as [取款|支付宝|金额], A.fCount_Take_S1 as [取款|支付宝|次数]
				 , A.fAmount_Take_S2 as [取款|微信|金额], A.fCount_Take_S2 as [取款|微信|次数]
				 , A.fAmount_Take_S3 as [取款|银联|金额], A.fCount_Take_S3 as [取款|银联|次数]
				 , A.fAmount_Take_S0 + A.fAmount_Take_S1 + A.fAmount_Take_S2 + A.fAmount_Take_S3 as [取款小计|金额]
				 , A.fCount_Take_S0 + A.fCount_Take_S1 + A.fCount_Take_S2 + A.fCount_Take_S3 as [取款小计|次数]
				  from
		  (
		  select 
			[fOperID]
			,[fPurseID]
			,CONVERT(varchar(10), fSettleTime, 120) as [fDate]
			,sum(case when (fRecType = 1) and (fSourceID = 0) then fAmount else 0 end) as [fAmount_Save_S0]
			,sum(case when (fRecType = 1) and (fSourceID = 0) then 1 else 0 end) as [fCount_Save_S0]
			,sum(case when (fRecType = 1) and (fSourceID = 1) then fAmount else 0 end) as [fAmount_Save_S1]
			,sum(case when (fRecType = 1) and (fSourceID = 1) then 1 else 0 end) as [fCount_Save_S1]
			,sum(case when (fRecType = 1) and (fSourceID = 2) then fAmount else 0 end) as [fAmount_Save_S2]
			,sum(case when (fRecType = 1) and (fSourceID = 2) then 1 else 0 end) as [fCount_Save_S2]
			,sum(case when (fRecType = 1) and (fSourceID = 3) then fAmount else 0 end) as [fAmount_Save_S3]
			,sum(case when (fRecType = 1) and (fSourceID = 3) then 1 else 0 end) as [fCount_Save_S3]
			,sum(case when (fRecType = 2) and (fSourceID = 0) then fAmount else 0 end) as [fAmount_Take_S0]
			,sum(case when (fRecType = 2) and (fSourceID = 0) then 1 else 0 end) as [fCount_Take_S0]
			,sum(case when (fRecType = 2) and (fSourceID = 1) then fAmount else 0 end) as [fAmount_Take_S1]
			,sum(case when (fRecType = 2) and (fSourceID = 1) then 1 else 0 end) as [fCount_Take_S1]
			,sum(case when (fRecType = 2) and (fSourceID = 2) then fAmount else 0 end) as [fAmount_Take_S2]
			,sum(case when (fRecType = 2) and (fSourceID = 2) then 1 else 0 end) as [fCount_Take_S2]
			,sum(case when (fRecType = 2) and (fSourceID = 3) then fAmount else 0 end) as [fAmount_Take_S3]
			,sum(case when (fRecType = 2) and (fSourceID = 3) then 1 else 0 end) as [fCount_Take_S3]
		  from ' + @sRet + '
			where [fSettleTime] >= ''' + @strB + ''' and [fSettleTime] <= ''' + @strE + ''' and [fRecType] in (1,2) ' + @Where +
		  '	group by fOperID, fPurseID, CONVERT(varchar(10), fSettleTime, 120)
		  ) A 
		  left join T_B_PurseCode PC on A.fPurseID = PC.fPurseCode
		  left join T_B_Manager M on A.fOperID = M.fOperID
		  ' + @Where1 + '
		  order by A.fOperID, A.fPurseID, A.fDate' 
	 --print @sqlstr  
	 exec(@sqlstr)  
end
go


create function dbo.fn_GetCurrentDBInfo ()
RETURNS @DBInfoTable TABLE
(
	ItemName varchar(100),
	ItemText varchar(200)
)
AS  
BEGIN 
declare @TmpValue varchar(200)
Insert @DBInfoTable Values('数据库名',db_name())
Insert @DBInfoTable Values('数据库服务器名',host_name())
select @TmpValue=fParamValue from T_B_SysParam where fParamName='DatabaseVersion'
Insert @DBInfoTable Values('数据库版本',@TmpValue)
select @TmpValue=convert(varchar(30),crdate,120) from master.dbo.sysdatabases where dbid=db_id()
Insert @DBInfoTable Values('数据库创建日期',@TmpValue)
select @TmpValue=[filename] from sysfiles where groupid=1
Insert @DBInfoTable Values('数据库数据文件',RTRIM(@TmpValue))
select @TmpValue=[size]*8 from sysfiles where groupid=1
Insert @DBInfoTable Values('数据库数据文件大小(KB)',@TmpValue)
select @TmpValue=[filename] from sysfiles where groupid=0
Insert @DBInfoTable Values('数据库日志文件',RTRIM(@TmpValue))
select @TmpValue=[size]*8 from sysfiles where groupid=0
Insert @DBInfoTable Values('数据库日志文件大小(KB)',@TmpValue)
select @TmpValue=fParamValue from T_B_SysParam where fParamName='BackupDatabasePath'
Insert @DBInfoTable Values('数据库自动备份文件存放路径',@TmpValue)
select @TmpValue=fParamValue from T_B_SysParam where fParamName='LastFullBackupDate'
Insert @DBInfoTable Values('最后一次完整备份时间',@TmpValue)
select @TmpValue=case when fReStrict=0 then '自动备份' else '手工备份'end from T_B_SysParam where fParamName='LastFullBackupDate'
Insert @DBInfoTable Values('最后一次完整备份方式',@TmpValue)
select @TmpValue=count(*) from sysobjects where xtype='U' and name<>'dtproperties'
Insert @DBInfoTable Values('数据库表数量',@TmpValue)
select @TmpValue=count(*) from sysobjects where xtype='P' and status>=0
Insert @DBInfoTable Values('数据库存储过程数量',@TmpValue)
select @TmpValue=count(*) from sysobjects where xtype in ('FN','TF','IF')
Insert @DBInfoTable Values('数据库函数数量',@TmpValue)
select @TmpValue=count(*) from sysobjects where xtype ='V' and status>=0
Insert @DBInfoTable Values('数据库视图数量',@TmpValue)

RETURN
END
go


create trigger dbo.TG_AutoAddDoor on dbo.T_B_Pos for insert
AS
declare @i int
declare @PosID int
declare @PosType int
declare @PosName varchar(20)
declare @MjType int

SELECT @PosID=fPosID,@PosType=fPosType,@PosName=fPosName,@MjType=fMJType FROM Inserted

if (@PosType=2)
begin
	declare @DoorCode varchar(7)
	declare @DoorCount int
	set @DoorCount=
		case 
		when @MjType=0 then 1
		when @MjType=1 then 2
		when @MjType=2 then 4
		else 4
		end
	set @i=1
	while @i<=@DoorCount 
	begin
		set @DoorCode= dbo.FN_FillZero(5,@PosID)+dbo.FN_FillZero(2,@i)
		Insert Into T_E_Door(fDoorID,fDoorName,fDoorCode,fPosID) 
		Values(@i,@PosName+Cast(@i as varchar(1))+'门',@DoorCode,@PosId)
		set @i=@i+1
	end
end
go


create trigger dbo.TG_AutoModifyDoor on dbo.T_B_Pos for update
AS
declare @i int
declare @PosID int
declare @PosType int
declare @PosName varchar(20)
declare @MjType int

SELECT @PosID=fPosID,@PosType=fPosType,@PosName=fPosName,@MjType=fMJType FROM Inserted

if (@PosType=2) and update(fMJType)
begin
	declare @DoorCode varchar(7)
	declare @DoorCount int
	set @DoorCount=
		case 
		when @MjType=0 then 1
		when @MjType=1 then 2
		when @MjType=2 then 4
		else 4
		end
	delete from T_E_Door where fPosID=@PosID and  fDoorID>@DoorCount 
	set @i=1
	while @i<=@DoorCount 
	begin
		set @DoorCode= dbo.FN_FillZero(5,@PosID)+dbo.FN_FillZero(2,@i)
		if not Exists (select * from T_E_Door where fPosID=@PosID and fDoorID=@i)
		Insert Into T_E_Door(fDoorID,fDoorName,fDoorCode,fPosID) 
		Values(@i,@PosName+Cast(@i as varchar(1))+'门',@DoorCode,@PosId)		
		set @i=@i+1
	end
end
go



------------------------------------插入默认值------------------------------------
insert into T_A_RecType (ftypeid,ftypeName) values (0,'所有类型')
insert into T_A_RecType (ftypeid,ftypeName) values (1,'正常打卡')
insert into T_A_RecType (ftypeid,ftypeName) values (2,'非正常打卡')
insert into T_A_RecType (ftypeid,ftypeName) values (3,'不在打卡时间')
insert into T_A_RecType (ftypeid,ftypeName) values (9,'人工打卡')
insert into T_A_RecType (ftypeid,ftypeName) values (51,'挂失卡')
insert into T_A_RecType (ftypeid,ftypeName) values (68,'锁定卡')
Go  


INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (99, N'所有类型')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (0, N'消费')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (1, N'存款')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (2, N'取款')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (3, N'补助')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (4, N'挂失')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (5, N'解挂')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (6, N'开户')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (7, N'有卡撤户')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (8, N'纠错')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (9, N'换卡')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (10, N'补卡')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (11, N'有卡变更')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (12, N'登陆')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (13, N'退出')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (14, N'未正常退出')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (15, N'黑名单刷新')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (16, N'改密码')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (17, N'脱机消费')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (18, N'删除流水')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (19, N'删除营业')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (20, N'删除出纳')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (21, N'自动挂失')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (22, N'无卡变更')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (23, N'人工冻结')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (24, N'自动冻结')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (25, N'无卡撤户')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (26, N'补发卡')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (27, N'解冻')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (28, N'圈存')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (29, N'圈存补款')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (30, N'圈提')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (31, N'优惠')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (32, N'计次')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (33, N'转入')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (34, N'转出')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (35, N'删除资料')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (36, N'销卡')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (37, N'补助清除')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (38, N'开卡')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (39, N'销卡')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (40, N'启用钱包')
INSERT [dbo].[T_C_ConsState] ([fStateID], [fStateName]) VALUES (41, N'停用钱包')
Go

INSERT [T_E_ErrType] ( [fTypeID] , [fTypeName] ) VALUES ( 0 , '所有类型' )
INSERT [T_E_ErrType] ( [fTypeID] , [fTypeName] ) VALUES ( 1 , 'RAM检测错误' )
INSERT [T_E_ErrType] ( [fTypeID] , [fTypeName] ) VALUES ( 2 , 'FLASH检测错误' )
INSERT [T_E_ErrType] ( [fTypeID] , [fTypeName] ) VALUES ( 3 , '无门禁机参数' )
INSERT [T_E_ErrType] ( [fTypeID] , [fTypeName] ) VALUES ( 4 , '无门参数' )
INSERT [T_E_ErrType] ( [fTypeID] , [fTypeName] ) VALUES ( 5 , '无读卡头参数' )
INSERT [T_E_ErrType] ( [fTypeID] , [fTypeName] ) VALUES ( 6 , '通行时段错误' )
INSERT [T_E_ErrType] ( [fTypeID] , [fTypeName] ) VALUES ( 7 , '通行规则不匹配' )
INSERT [T_E_ErrType] ( [fTypeID] , [fTypeName] ) VALUES ( 8 , '无人员信息' )
INSERT [T_E_ErrType] ( [fTypeID] , [fTypeName] ) VALUES ( 9 , '人员信息无效' )
INSERT [T_E_ErrType] ( [fTypeID] , [fTypeName] ) VALUES ( 10 , '人员过期' )
INSERT [T_E_ErrType] ( [fTypeID] , [fTypeName] ) VALUES ( 11 , '规则ID错误' )
INSERT [T_E_ErrType] ( [fTypeID] , [fTypeName] ) VALUES ( 12 , '规则无效' )
INSERT [T_E_ErrType] ( [fTypeID] , [fTypeName] ) VALUES ( 13 , '门参数ID不匹配' )
INSERT [T_E_ErrType] ( [fTypeID] , [fTypeName] ) VALUES ( 14 , '通行时段不匹配' )
INSERT [T_E_ErrType] ( [fTypeID] , [fTypeName] ) VALUES ( 15 , '操作类型错误' )
INSERT [T_E_ErrType] ( [fTypeID] , [fTypeName] ) VALUES ( 16 , 'FLASH ROM满' )
INSERT [T_E_ErrType] ( [fTypeID] , [fTypeName] ) VALUES ( 17 , '用户指针错误' )
INSERT [T_E_ErrType] ( [fTypeID] , [fTypeName] ) VALUES ( 18 , '开门失败' )
INSERT [T_E_ErrType] ( [fTypeID] , [fTypeName] ) VALUES ( 19 , '互锁' )
INSERT [T_E_ErrType] ( [fTypeID] , [fTypeName] ) VALUES ( 20 , '防尾随' )
INSERT [T_E_ErrType] ( [fTypeID] , [fTypeName] ) VALUES ( 21 , '密码错误' )
INSERT [T_E_ErrType] ( [fTypeID] , [fTypeName] ) VALUES ( 22 , '卡不匹配非开门卡' )
INSERT [T_E_ErrType] ( [fTypeID] , [fTypeName] ) VALUES ( 23 , '工作电压低' )
INSERT [T_E_ErrType] ( [fTypeID] , [fTypeName] ) VALUES ( 24 , '门超出限定' )
INSERT [T_E_ErrType] ( [fTypeID] , [fTypeName] ) VALUES ( 25 , '非进出门读卡头' )
Go

INSERT [T_E_RecType] ( [fTypeID] , [fTypeName] ) VALUES ( 0 , '所有类型' )
INSERT [T_E_RecType] ( [fTypeID] , [fTypeName] ) VALUES ( 1 , '开锁' )
INSERT [T_E_RecType] ( [fTypeID] , [fTypeName] ) VALUES ( 2 , '关锁' )
INSERT [T_E_RecType] ( [fTypeID] , [fTypeName] ) VALUES ( 3 , '报警' )
INSERT [T_E_RecType] ( [fTypeID] , [fTypeName] ) VALUES ( 4 , '考勤打卡' )
INSERT [T_E_RecType] ( [fTypeID] , [fTypeName] ) VALUES ( 5 , '巡更' )
INSERT [T_E_RecType] ( [fTypeID] , [fTypeName] ) VALUES ( 6 , '关门超时' )
INSERT [T_E_RecType] ( [fTypeID] , [fTypeName] ) VALUES ( 7 , '开门超时' )
INSERT [T_E_RecType] ( [fTypeID] , [fTypeName] ) VALUES ( 8 , '胁迫开门' )
INSERT [T_E_RecType] ( [fTypeID] , [fTypeName] ) VALUES ( 9 , '胁迫关门' )
INSERT [T_E_RecType] ( [fTypeID] , [fTypeName] ) VALUES ( 10 , '非法开门' )
INSERT [T_E_RecType] ( [fTypeID] , [fTypeName] ) VALUES ( 11 , '关报警' )
INSERT [T_E_RecType] ( [fTypeID] , [fTypeName] ) VALUES ( 12 , '按钮开门' )
INSERT [T_E_RecType] ( [fTypeID] , [fTypeName] ) VALUES ( 13 , '超级密码开门' )
INSERT [T_E_RecType] ( [fTypeID] , [fTypeName] ) VALUES ( 14 , '普通密码开门' )
INSERT [T_E_RecType] ( [fTypeID] , [fTypeName] ) VALUES ( 15 , '无效刷卡(卡到期或规则不允许)' )
INSERT [T_E_RecType] ( [fTypeID] , [fTypeName] ) VALUES ( 16 , '非法打卡' )
INSERT [T_E_RecType] ( [fTypeID] , [fTypeName] ) VALUES ( 17 , '门打开' )
INSERT [T_E_RecType] ( [fTypeID] , [fTypeName] ) VALUES ( 18 , '门关闭' )
INSERT [T_E_RecType] ( [fTypeID] , [fTypeName] ) VALUES ( 19 , '非法卡报警' )
INSERT [T_E_RecType] ( [fTypeID] , [fTypeName] ) VALUES ( 20 , '无效时间刷卡' )
INSERT [T_E_RecType] ( [fTypeID] , [fTypeName] ) VALUES ( 21 , '门互锁开门失败' )
INSERT [T_E_RecType] ( [fTypeID] , [fTypeName] ) VALUES ( 22 , '防尾随开门失败' )
INSERT [T_E_RecType] ( [fTypeID] , [fTypeName] ) VALUES ( 23 , '工作电压低' )
INSERT [dbo].[T_E_RecType] ([fTypeID], [fTypeName]) VALUES (101, N'卡号无效')
INSERT [dbo].[T_E_RecType] ([fTypeID], [fTypeName]) VALUES (102, N'非法打开')
INSERT [dbo].[T_E_RecType] ([fTypeID], [fTypeName]) VALUES (103, N'卡过有效期')
INSERT [dbo].[T_E_RecType] ([fTypeID], [fTypeName]) VALUES (104, N'门号无效')
INSERT [dbo].[T_E_RecType] ([fTypeID], [fTypeName]) VALUES (105, N'规则号无效')
INSERT [dbo].[T_E_RecType] ([fTypeID], [fTypeName]) VALUES (106, N'工作通用规则无效电压低')
INSERT [dbo].[T_E_RecType] ([fTypeID], [fTypeName]) VALUES (107, N'通用规则通用时段无效')
INSERT [dbo].[T_E_RecType] ([fTypeID], [fTypeName]) VALUES (108, N'自定义规则通行时段无效')
INSERT [dbo].[T_E_RecType] ([fTypeID], [fTypeName]) VALUES (113, N'开门失败')
Go

INSERT [T_B_ManType] ( [fId_TypeId] , [fId_TypeName] , [fKh_Money] , [fKh_Charge] , [fCh_Charge] , [fHk_Charge] , [fBk_Charge] , [fBk_Money] , [fGs_Charge] , [fJg_Charge] , [fUes_PassMoney] , [fManage_Charge] , [fsubsity_money] , [fcons_Group] , [fparent] ) 
VALUES ( 0 , '操作员' , .00 , .00 , .00 , .00 , .00 , .00 , .00 , .00 , .00 , .00 , .00 , '0' , 0 )
Go

INSERT [dbo].[T_B_PurseCode] ([fPurseCode], [fPurseName], [fPurseType], [fRechargeType], [fOnLine], [fState], [fLimitEnabled], [fBottomLine], [fIsMain], [fM1Addr],[fDayLimitMoney]) VALUES (1, N'主钱包', 0, 0, 1, 1, 0, 0.0000, 1, 16,0)
GO

INSERT [dbo].[T_B_CardType] ([fCardTypeID], [fCardTypeName], [fIsMainCard], [fCardType], [fFirstPurseID], [fSecondPurseID], [fState], [fDeposit]) VALUES (1, N'主卡', 1, 0, 1, 2, 1, 0.0000)
GO

 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fRestrict] , [fExplain] ) VALUES ( 'AccountLength' , '8' , 'Integer' , '&p>=4 and &p<=18' , '帐号长度(不能低于4位)' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fRestrict] , [fExplain] ) VALUES ( 'Atd_TimeDiff' , '0' , 'byte' , '' , '考勤参数' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fExplain] ) VALUES ( 'ATDMuchCard' , '0' , 'Integer' , '考勤启用一户多卡' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fExplain] ) VALUES ( 'AutoRestartEnable' , '0' , 'Integer' , '是否自动重启' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fExplain] ) VALUES ( 'AutoRestartTime' , '41137.25' , 'DateTime' , '自动重启时间' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fRestrict] , [fExplain] ) VALUES ( 'BackupDatabasePath' , 'D:\一卡通系统\ID1.0.3.2\PplatManager\' , 'string' , '' , '数据库备份地址' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fExplain] ) VALUES ( 'CardClass' , '0' , 'Integer' , '读头类型' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fExplain] ) VALUES ( 'CardLength' , '8' , 'Integer' , '卡号长度' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fRestrict] , [fExplain] ) VALUES ( 'cp_CurrentlyKey' , '1F46CC57ACD4235BF96582EB72' , 'string' , 'Length(&p)=12' , '卡当前密码' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fExplain] ) VALUES ( 'cp_PassType' , '0' , 'Byte' , '使用密码类型' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fRestrict] , [fExplain] ) VALUES ( 'cp_PrimaryKey' , '52BB42CC224EACC05F80EF151B' , 'string' , 'Length(&p)=12' , '卡初始密码' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fExplain] ) VALUES ( 'cp_Sevtor' , '3' , 'Byte' , '读卡扇区' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fExplain] ) VALUES ( 'DatabaseVersion' , '201212010900' , 'varchar' , '数据库版本' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fExplain] ) VALUES ( 'EGSMuchCard' , '0' , 'Integer' , '门禁启用一户多卡' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fRestrict] , [fExplain] ) VALUES ( 'EndianType' , '0' , 'Byte' , '' , '门禁卡号存放类型' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fRestrict] , [fExplain] ) VALUES ( 'LastFullBackupDate' , '06 15 2015  4:23PM' , 'DateTime' , '0' , '最后一次完整备份日期' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fExplain] ) VALUES ( 'LastSubID' , '0' , 'Integer' , '最后一次补助ID' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fRestrict] , [fExplain] ) VALUES ( 'LostType' , '0' , 'Byte' , '' , '挂失方式' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fExplain] ) VALUES ( 'MaxAccountID' , '0' , 'string' , '系统中最大帐号值' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fExplain] ) VALUES ( 'MaxCardID' , '0' , 'string' , '系统中最大卡号值' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fExplain] ) VALUES ( 'MonthBegin' , '1' , 'Integer' , '月起始时间' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fExplain] ) VALUES ( 'RecCount' , '0' , 'Integer' , '流水最大的记录数' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fExplain] ) VALUES ( 'RepeatTime' , '2' , 'Integer' , '重复刷卡时限' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fRestrict] , [fExplain] ) VALUES ( 'SecurityCode' , '65535' , 'word' , '' , '门禁参数' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fRestrict] , [fExplain] ) VALUES ( 'UnitAddress' , '' , 'string' , '' , '用户地址' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fRestrict] , [fExplain] ) VALUES ( 'UnitCode' , '51010001' , 'string' , '' , '企业编号' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fRestrict] , [fExplain] ) VALUES ( 'UnitName' , '请填写用户名称' , 'string' , '' , '使用用户名称' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fRestrict] , [fExplain] ) VALUES ( 'UnitPhone' , '' , 'string' , '' , '联系电话' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fRestrict] , [fExplain] ) VALUES ( 'UnitPostalcode' , '' , 'string' , '' , '邮编' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fRestrict] , [fExplain] ) VALUES ( 'UnitPrincipal' , '' , 'string' , '' , '负责人' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fExplain] ) VALUES ( 'UseCardRuleID' , '[0],' , 'string' , '已使用的打卡规则编号' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fExplain] ) VALUES ( 'UseDeptID' , '' , 'string' , '已使用的部门编号' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fExplain] ) VALUES ( 'UseManTypeID' , '' , 'string' , '已使用的卡类型编号' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fExplain] ) VALUES ( 'UseRingID' , '[0],' , 'string' , '已使用的响铃规则编号' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fExplain] ) VALUES ( 'UseStationID' , '[1],' , 'string' , '已使用的工作站编码' )
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fExplain] ) VALUES('PlatScriptVersion','20220809104451','String','平台脚本版本号') 
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fExplain] ) VALUES('ReportScriptVersion','20210604173200','String','报表脚本版本号')
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fExplain] ) VALUES('LastRunTime','0','Datetime','最后登录时间')
 INSERT [T_B_SysParam] ( [fParamName] , [fParamValue] , [fParamType] , [fRestrict] , [fExplain] ) VALUES('SysMonthAccountDate', 0, 'int', null, '系统月结算日期，0：表示自然月；1-28：结算日期；其余数字为非法')
Go


INSERT INTO [T_B_MealSet] ([fMeal_Id], [fMeal_Name], [fBegin_Time], [fEnd_Time], [fLimitBc])
                   VALUES ('001', '早餐','1899-12-30 00:00:00','1899-12-30 09:30:00',0)
INSERT INTO [T_B_MealSet] ([fMeal_Id], [fMeal_Name], [fBegin_Time], [fEnd_Time], [fLimitBc])
                   VALUES ('002', '午餐','1899-12-30 09:30:01','1899-12-30 14:00:00',0)
INSERT INTO [T_B_MealSet] ([fMeal_Id], [fMeal_Name], [fBegin_Time], [fEnd_Time], [fLimitBc])
                   VALUES ('003', '晚餐','1899-12-30 14:00:01','1899-12-30 20:00:00',0)
INSERT INTO [T_B_MealSet] ([fMeal_Id], [fMeal_Name], [fBegin_Time], [fEnd_Time], [fLimitBc])
                   VALUES ('004', '夜宵','1899-12-30 20:00:01','1899-12-30 23:59:59',0)                                                         
GO


SET IDENTITY_INSERT T_B_Manager ON  
Go 
if not exists (select * from T_B_Manager where fOperID = 99999) 
INSERT INTO [T_B_Manager]
           ([fOperID], [fOperName], [fLoginName], [fOperPass], [fDeptCode]
          , [fStationId], [fUsefulLife], [fPermanent], [fLocked], [fIsManager]
          , [fCardNo], [fCardPass], [fDesc], [fReportRight], [fRight])
     VALUES
           (99999, '后台系统', '', '5B9F4de5df56EFA', ''
           , '', '', 0, 1, 0
           , '', '', '', '', 0x4400000006000000D6F7B3CCD0F20000000008000000D3C3BBA7B5C7C2BC000000000A000000B2D9D7F7D4B1B9DCC0ED0000000008000000D3C3BBA7B9DCC0ED0000000008000000B8F6B1F0BFAABBA7000000000C000000B8F6C8CBD5CBBBA7D0DEB8C40000000012000000C9BEB3FDCEB4B7A2BFA8D3C3BBA7D7CAC1CF0000000008000000B8F6B1F0B3B7BBA70000000008000000B8F6B1F0C5E4BFA80000000008000000C5FAC1BFB3B7BBA70000000010000000C5FAC1BFC9BEB3FDD3C3BBA7D7CAC1CF000000000C000000C5FAC1BFD5CBBBA7D0DEB8C40000000008000000C5FAC1BFC5E4BFA80000000008000000D5CBBBA7B9DCC0ED000000000C000000CAFDBEDDB1B8B7DDB9DCC0ED000000000C000000B2D9D7F7D4B1BFA8B9DCC0ED0000000008000000BFBCC7DAB9DCC0ED000000000C000000BFBCC7DAD6C6B6C8B9DCC0ED0000000008000000B0E0B4CEB9DCC0ED000000000C000000C5C5B0E0B9E6C2C9B9DCC0ED0000000010000000BFBCC7DAB4F2BFA8B9E6D4F2B9DCC0ED0000000008000000CFECC1E5C9E8D6C30000000008000000C5C5B0E0B9DCC0ED0000000008000000C5C5B0E0B2D9D7F70000000008000000C7EBBCD9B9DCC0ED0000000008000000BCD3B0E0B9DCC0ED0000000008000000B3F6B2EEB9DCC0ED0000000008000000C8CBB9A4B4F2BFA8000000000C000000C9FAB3C9BFBCC7DACAFDBEDD0000000010000000BFBCC7DACAFDBEDDD7D6B5E4C9E8D6C30000000008000000C3C5BDFBB9DCC0ED000000000C000000CDA8D0D0B9E6D4F2B9DCC0ED0000000010000000C8CBD4B1CDA8D0D0CADAC8A8B9DCC0ED0000000008000000BBF9B4A1C9E8D6C3000000000C000000CFB5CDB3B2CECAFDC5E4D6C3000000000E000000B9A4D7F7D5BEBCDCB9B9C9E8D6C3000000000C000000C8CBD4B1B2BFC3C5C9E8D6C30000000008000000C3DCC2EBD0DEB8C4000000000C000000BBF9B4A1CAFDBEDDD7D6B5E4000000000C000000C9EDB7DDB2CECAFDC9E8D6C3000000000A000000BDDABCD9C8D5B9DCC0ED000000000C000000D3AAD2B5B2CECAFDC9E8D6C3000000000C000000D3AAD2B5B0E0B4CEC9E8D6C30000000010000000C9EDB7DDB2CDB4CECFDEB4CEC9E8D6C30000000008000000B2B9D6FAB9DCC0ED000000000E000000CEB4C8B7C8CFC1F7CBAEB4A6C0ED0000000008000000C9E8B1B8B9DCC0ED000000000C000000B6C1BFA8C9E8B1B8B9DCC0ED000000000C000000D3AAD2B5C9E8B1B8B9DCC0ED0000000028000000B6D4B3F6C4C9BBFAB5C4C5E4D6C3D3EBB9DCC0EDA3ACD2D4BCB0CFE0B9D8B2CECAFDB5C4CFC2D4D8000000000C000000BFD8CBAEC9E8B1B8B9DCC0ED000000000C000000BFBCC7DAC9E8B1B8B9DCC0ED000000000C000000C3C5BDFBC9E8B1B8B9DCC0ED0000000014000000BADAB0D7C3FBB5A5CFC2D4D8C7E9BFF6BCE0BFD80000000010000000BADAB0D7C3FBB5A5CAD6B9A4CFC2D4D8000000000F000000B6C1C8A1CFFBB7D1555342CAFDBEDD000000000F000000B6C1C8A1BFBCC7DA555342CAFDBEDD0000000006000000BFA8B9DCC0ED000000000A000000BFA8C5FAB4CEC9E8D6C30000000004000000B9D2CAA70000000004000000BDE2B9D20000000004000000BBBBBFA80000000004000000B2B9BFA80000000008000000BFA8C6ACD7A2CFFA0000000008000000D7A2CFFABFA8C6AC0000000004000000B3E4D6B50000000004000000C8A1BFEE0000000008000000CFFBB7D1BEC0B4ED00000000)
GO
SET IDENTITY_INSERT T_B_Manager OFF
Go

--VALUES_EDIT_2 修改表T_R_Group中的数据
insert into T_R_Group ( fRSGroupCode, fRSGroupName, fRSGroupLevel, fRSRemark) values 
	( '001' , '考勤报表' , 0, 'Atd' ) 
insert into T_R_Group ( fRSGroupCode, fRSGroupName, fRSGroupLevel, fRSRemark) values 
	( '002' , '消费报表' , 0, 'Cns' ) 
insert into T_R_Group ( fRSGroupCode, fRSGroupName, fRSGroupLevel, fRSRemark) values 
	( '003' , '门禁报表' , 0, 'Egs' ) 
insert into T_R_Group ( fRSGroupCode, fRSGroupName, fRSGroupLevel, fRSRemark) values 
	( '004' , '基本报表' , 0, 'Bas' ) 
insert into T_R_Group ( fRSGroupCode, fRSGroupName, fRSGroupLevel, fRSRemark) values 
	( '005' , '卡务报表' , 0, 'Crd' ) 
insert into T_R_Group ( fRSGroupCode, fRSGroupName, fRSGroupLevel, fRSRemark) values 
	( '002001' , '营业报表' , 1, '' ) 
insert into T_R_Group ( fRSGroupCode, fRSGroupName, fRSGroupLevel, fRSRemark) values 
	( '002002' , '出纳报表' , 1, '' ) 
insert into T_R_Group ( fRSGroupCode, fRSGroupName, fRSGroupLevel, fRSRemark) values 
	( '002003' , '分类明细报表' , 1, '' ) 
insert into T_R_Group ( fRSGroupCode, fRSGroupName, fRSGroupLevel, fRSRemark) values 
	( '002004' , '分类统计报表' , 1, '' ) 
/*	
insert into T_R_Group ( fRSGroupCode, fRSGroupName, fRSGroupLevel, fRSRemark) values 
	( '002005' , '补助报表' , 1, '' ) 
*/	


--VALUES_EDIT_3 修改表T_R_Report中的数据
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_M' , 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, '002005' , '' , 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_Cns_SysAccont_Month' , 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_Report ( fReportID, fReportName, fReportProc, fReportType, fGroupID, ffr3fileName, fDisPlay, fDefaultDis, fPrintDirection, fColUnDis, fColFix, fTotleDis, fHide, fRemark) values 
    ( 28, '出纳存取款(来源)汇总表' , 'UP_Report_Cns_Total_CashSource' , 2, '002002' , '' , 1, 2 , 1, '' , null , 'S3|S4|S5|S6|S7|S8|S9|S10|S11|S12|S13|S14|S15|S16|S17|S18|S19|S20|S21|S22' , 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 T_R_Dict(fDictType,fDictName,fSerialNO,fDisplayName,fFootType,fDictContent,fMask,fMax,fMin,fDictDefault,fIsCheck,fIsPrint,fIsScript,fReportID,fRemark)
  values(4,'fYear',1,'年份',0,NULL,NULL,2099,2000,'toyear',NULL,1,NULL,9,'请选择年份')
  
insert T_R_Dict(fDictType,fDictName,fSerialNO,fDisplayName,fFootType,fDictContent,fMask,fMax,fMin,fDictDefault,fIsCheck,fIsPrint,fIsScript,fReportID,fRemark)
  values(4,'fMonth',2,'月份',0,NULL,NULL,12,1,'tomonth',NULL,1,NULL,9,'请选择月份') 
  
insert T_R_Dict(fDictType,fDictName,fSerialNO,fDisplayName,fFootType,fDictContent,fMask,fMax,fMin,fDictDefault,fIsCheck,fIsPrint,fIsScript,fReportID,fRemark)
  values(11,'R.fPurseID',3,'钱包选择',1,'select  * from T_B_PurseCode|T_B_PurseCode|fPurseCode|fPurseName',NULL,null,null,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 T_R_Dict(fDictType,fDictName,fSerialNO,fDisplayName,fFootType,fDictContent,fMask,fMax,fMin,fDictDefault,fIsCheck,fIsPrint,fIsScript,fReportID,fRemark)
	values(4,'fYear',1,'年份',0,NULL,NULL,2099,2000,'toyear',NULL,1,NULL,22,'请选择年份')
  
insert T_R_Dict(fDictType,fDictName,fSerialNO,fDisplayName,fFootType,fDictContent,fMask,fMax,fMin,fDictDefault,fIsCheck,fIsPrint,fIsScript,fReportID,fRemark)
	values(4,'fMonth',2,'月份',0,NULL,NULL,12,1,'tomonth',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, '' ) 
			
  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 , 28, '多选操作员' ) 
  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 , 28, '查询开始日期' ) 
  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 , 28, '查询结束日期' )  			
			
			
INSERT INTO [T_A_CheckRule]([fCheckSystemCode], [fCheckSystemName], [fAllowOverdue], [fAllowLeaveEarly], [fOnDutyBefore], [fOnDutyAfter], [fOffDutyBefore], [fOffDutyAfter], [fOffDutyLast], [fOffDutyDeferEnable], [fSubtractAbsenceTime], [fOffDayIsWeek], [fCheckOffDay], [fOffDay], [fOffDayCalcOvertime], [fCheckOvertime], [fWorkTimeUnit], [fWorkTimeMode], [fOvertimeUnit], [fOverTimeMode], [fAbsenceTimeUnit], [fAbsenceTimeMode], [fLeaveTimeUnit], [fLeaveTimeMode], [fDayOfAbsentMinutes], [fDayOfLeaveMinutes], [fMultipleOfNormal], [fMultipleOfOffDay], [fMultipleOfHoliDay], [fCompulsory], [fOverTimeDuration], [fIsDefault])VALUES('1', '默认制度', 0, 0, 60, 60, 60, 60, 0, 0, 1, 1, 0, '|星期六|星期日', 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 240, 240, 1.00, 1.00, 1.00, 0, 0, 0)


--VALUES_EDIT_5 修改表T_R_ReportRela中的数据
insert into T_R_ReportRela ( fRelaID, fReportParentID, fReportChildID, fIsDisPlay) values 
	( 1, 36, 10, 1) 

--VALUES_EDIT_6 修改表T_R_DictRela中的数据
insert into T_R_DictRela ( fRelaID, fSouDictID, fDesDictID, fMark) values 
	( 1, 0, 35, 'ToDay' ) 
insert into T_R_DictRela ( fRelaID, fSouDictID, fDesDictID, fMark) values 
	( 1, -1, 36, '账号' ) 
GO

--默认生成01工作站临时缓存表
Exec SP_Cash_CheckRecTable '01'  
Go