
IF (SELECT VERSION FROM  ACCINFO  WHERE GUID='0001' ) < '7.3'  
BEGIN

ALTER TABLE STORECGDDD ADD	[WCUnitQty] [decimal](18,  4) NULL 
ALTER TABLE STORECGDDD ADD	[WCQuantity] [decimal](18,  4) NULL 
ALTER TABLE STORECGDDD ADD	[ZZUnitQty] [decimal](18,  4) NULL 
ALTER TABLE STORECGDDD ADD	[ZZQuantity] [decimal](18,  4) NULL 
ALTER TABLE STORECGDDD ADD	[DXSPrice] [numeric](18 , 2) NULL 
ALTER TABLE STORECGDDD ADD	[MXSPrice] [numeric](18 , 2) NULL 
END

----------ENDFLAG
IF (SELECT VERSION FROM  ACCINFO  WHERE GUID='0001' ) < '7.3'  
BEGIN

ALTER TABLE STOREXSDDD ADD	[WCUnitQty] [decimal](18,  4) NULL 
ALTER TABLE STOREXSDDD ADD	[WCQuantity] [decimal](18,  4) NULL 
ALTER TABLE STOREXSDDD ADD	[ZZUnitQty] [decimal](18,  4) NULL 
ALTER TABLE STOREXSDDD ADD	[ZZQuantity] [decimal](18,  4) NULL 
ALTER TABLE STOREXSDDD ADD	[DXSPrice] [numeric](18 , 2) NULL 
ALTER TABLE STOREXSDDD ADD	[MXSPrice] [numeric](18 , 2) NULL 
END

----------ENDFLAG
IF (SELECT VERSION FROM  ACCINFO  WHERE GUID='0001' ) < '7.3'  
BEGIN

ALTER TABLE STOREXSCKD ADD	[RECODE] [varchar](50) NULL 
ALTER TABLE STOREXSCKD ADD	[REITEMNO] [varchar](50) NULL 
ALTER TABLE STOREXSCKD ADD	[DXSPrice] [numeric](18 , 2) NULL 
ALTER TABLE STOREXSCKD ADD	[MXSPrice] [numeric](18 , 2) NULL 
END

----------ENDFLAG
IF (SELECT VERSION FROM  ACCINFO  WHERE GUID='0001' ) < '7.3'  
BEGIN

ALTER TABLE STOREXSTHD ADD	[RECODE] [varchar](50) NULL 
ALTER TABLE STOREXSTHD ADD	[REITEMNO] [varchar](50) NULL 
ALTER TABLE STOREXSTHD ADD	[DXSPrice] [numeric](18 , 2) NULL 
ALTER TABLE STOREXSTHD ADD	[MXSPrice] [numeric](18 , 2) NULL 
END

----------ENDFLAG
IF (SELECT VERSION FROM  ACCINFO  WHERE GUID='0001' ) < '7.3'  
BEGIN

ALTER TABLE STORECGRKD ADD	[RECODE] [varchar](50) NULL 
ALTER TABLE STORECGRKD ADD	[REITEMNO] [varchar](50) NULL 
ALTER TABLE STORECGRKD ADD	[DXSPrice] [numeric](18 , 2) NULL 
ALTER TABLE STORECGRKD ADD	[MXSPrice] [numeric](18 , 2) NULL 
END

----------ENDFLAG
IF (SELECT VERSION FROM  ACCINFO  WHERE GUID='0001' ) < '7.3'  
BEGIN

ALTER TABLE STORECGTHD ADD	[RECODE] [varchar](50) NULL 
ALTER TABLE STORECGTHD ADD	[REITEMNO] [varchar](50) NULL 
ALTER TABLE STORECGTHD ADD	[DXSPrice] [numeric](18 , 2) NULL 
ALTER TABLE STORECGTHD ADD	[MXSPrice] [numeric](18 , 2) NULL 

END

----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWCGRK_2014]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWCGRK_2014]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWCGRKGOODSCODE]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWCGRKGOODSCODE]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWCGRK_Sum]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWCGRK_Sum]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWCKDBBILLJSNO]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWCKDBBILLJSNO]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWCKDBGOODSCODE]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWCKDBGOODSCODE]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWCKPDBILLJSNO]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWCKPDBILLJSNO]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWCKPDGOODSCODE]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWCKPDGOODSCODE]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWFYKZJSNO]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWFYKZJSNO]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWGJRKGOODSCODE]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWGJRKGOODSCODE]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWQTCKGOODSCODE]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWQTCKGOODSCODE]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWQTRKGOODSCODE]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWQTRKGOODSCODE]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWQTSRJSNO]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWQTSRJSNO]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWXSCKGOODSCODE]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWXSCKGOODSCODE]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWYunFeiMXB]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWYunFeiMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEW_CW_PingZheng_Code4]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEW_CW_PingZheng_Code4]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWCGRK]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWCGRK]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWCKDB]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWCKDB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWCKPD]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWCKPD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWDETAILBILLFLOWJSNO]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWDETAILBILLFLOWJSNO]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWFYKZ]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWFYKZ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWGJRK]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWGJRK]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWGOODS_ZaiTu]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWGOODS_ZaiTu]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWQTCK]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWQTCK]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWQTRK]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWQTRK]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWQTSR]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWQTSR]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWXSCK]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWXSCK]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWXSCKGOODSCODE_2011]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWXSCKGOODSCODE_2011]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWXSCK_2014]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWXSCK_2014]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEW_CW_PingZheng]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEW_CW_PingZheng]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ViewCGDD]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[ViewCGDD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[ViewXSDD]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[ViewXSDD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWAreaClient]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWAreaClient]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWAreavendor]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWAreavendor]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWBILL]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWBILL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWCGRKM]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWCGRKM]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWCGRKM_CGTHM]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWCGRKM_CGTHM]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWCLIENT]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWCLIENT]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWCLIENTBILLFLOW]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWCLIENTBILLFLOW]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWCLIENTJSNO]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWCLIENTJSNO]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWClient2013]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWClient2013]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWGOODSJSNO]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWGOODSJSNO]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWGOODSTYPEGOODSTREE]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWGOODSTYPEGOODSTREE]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWVENDOR]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWVENDOR]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWXSCKM]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWXSCKM]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWXSCKM_XSTHM]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWXSCKM_XSTHM]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWXSCK_2011]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWXSCK_2011]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEW_CW_BILLFLOW]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEW_CW_BILLFLOW]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWvendorJSNO]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWvendorJSNO]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VIEWXSCK_Sum]') and OBJECTPROPERTY(id, N'IsView') = 1)
drop view [dbo].[VIEWXSCK_Sum]
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG



CREATE VIEW dbo.VIEWXSCK
AS
SELECT dbo.STOREXSCKM.*, dbo.STOREXSCKD.ITEMNO, dbo.STOREXSCKD.STOREID, 
      dbo.STOREXSCKD.GOODSID, dbo.STOREXSCKD.APRICE, dbo.STOREXSCKD.PRICE, 
      dbo.STOREXSCKD.QUANTITY, 
      dbo.STOREXSCKD.DETAILBILLFLOWID, 
      dbo.STOREXSCKD.REDETAILBILLFLOWID,
      dbo.STOREXSCKD.UNITPRICE,
      dbo.STOREXSCKD.UNITQTY,
      dbo.STOREXSCKD.DISC,
      dbo.STOREXSCKD.AMT,
      dbo.STOREXSCKD.TAXAMT,
      dbo.STOREXSCKD.PRICETYPE,
      dbo.STOREXSCKD.TAXRATE,
      dbo.STOREXSCKD.ChanDi,
      dbo.STOREXSCKD.FuZhuQTY,
      dbo.STOREXSCKD.specnameD,
      dbo.STOREXSCKD.CaiZhi
FROM dbo.STOREXSCKD INNER JOIN
      dbo.STOREXSCKM ON dbo.STOREXSCKD.BILLID = dbo.STOREXSCKM.BILLID
WHERE FLAGPOST = 1 


UNION


SELECT dbo.STOREXSTHM.*, dbo.STOREXSTHD.ITEMNO, dbo.STOREXSTHD.STOREID, 
      dbo.STOREXSTHD.GOODSID, dbo.STOREXSTHD.APRICE, dbo.STOREXSTHD.PRICE, 
      -dbo.STOREXSTHD.QUANTITY  AS QUANTITY,
      dbo.STOREXSTHD.DETAILBILLFLOWID, 
      dbo.STOREXSTHD.REDETAILBILLFLOWID,
      dbo.STOREXSTHD.UNITPRICE,
      -dbo.STOREXSTHD.UNITQTY    as unitqty,
      dbo.STOREXSTHD.DISC,
      -dbo.STOREXSTHD.AMT   AS AMT,   
      -dbo.STOREXSTHD.TAXAMT    AS TAXAMT,
      dbo.STOREXSTHD.PRICETYPE,
      dbo.STOREXSTHD.TAXRATE,
      dbo.STOREXSTHD.ChanDi,
      dbo.STOREXSTHD.FuZhuQTY,
      dbo.STOREXSTHD.specnameD,
      dbo.STOREXSTHD.CaiZhi
FROM dbo.STOREXSTHD INNER JOIN
      dbo.STOREXSTHM ON dbo.STOREXSTHD.BILLID = dbo.STOREXSTHM.BILLID
WHERE FLAGPOST = 1 










































----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG




CREATE VIEW dbo.VIEWXSCK_Sum
AS
SELECT  BILLID,CLIENTID,BILLDATE,BILLType,ClientFlag,BumenID,Memo,EMPID,
sum(AMT) AS   AMT,sum(TaxAMT) as TaxAMT 
From VIEWXSCK
GROUP BY BILLID,CLIENTID,BILLDATE,BILLType,ClientFlag,BumenID,Memo,EMPID



----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG






















CREATE VIEW dbo.VIEWAreaClient
AS
SELECT LCODE, Prevno,NAME,LCODE AS LCODE00
FROM Area
UNION
SELECT clientid  AS LCODE, AREAID AS Prevno, NAME,code  AS LCODE00
FROM client


















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG



















CREATE VIEW dbo.VIEWAreavendor
AS
SELECT LCODE, Prevno,NAME,LCODE AS LCODE00
FROM Area
UNION
SELECT vendorid  AS LCODE, AREAID AS Prevno, NAME,code  AS LCODE00
FROM vendor

















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG




















CREATE VIEW dbo.VIEWBILL
AS
	SELECT BILLID, YYYYMM, BILLTYPE, VENDORID, CLIENTID, POSTMAN, CODE, BILLDATE, 
      MAKEMAN, FLAGPOST, MEMO, STATUS, INOUTFLAG, OLDBILLCODE,EMPID,BUMENID
	FROM STORECGRKM
	UNION
	SELECT BILLID, YYYYMM, BILLTYPE, VENDORID, CLIENTID, POSTMAN, CODE, BILLDATE, 
      MAKEMAN, FLAGPOST, MEMO, STATUS, INOUTFLAG, OLDBILLCODE,EMPID,BUMENID
	FROM STOREXSCKM
	UNION
	SELECT BILLID, YYYYMM, BILLTYPE, VENDOR_CLIENT_ID as VENDORID, VENDOR_CLIENT_ID as CLIENTID, POSTMAN, CODE, BILLDATE, 
      MAKEMAN, FLAGPOST, MEMO, STATUS, INOUTFLAG, OLDBILLCODE,EMPID,BUMENID
	FROM STORECGFKM
	UNION
	SELECT BILLID, YYYYMM, BILLTYPE, VENDOR_CLIENT_ID as VENDORID, VENDOR_CLIENT_ID as CLIENTID, POSTMAN, CODE, BILLDATE, 
      MAKEMAN, FLAGPOST, MEMO, STATUS, INOUTFLAG, OLDBILLCODE,EMPID,BUMENID
	FROM STOREXSSKM
	UNION
	SELECT BILLID, YYYYMM, BILLTYPE, VENDORID, CLIENTID, POSTMAN, CODE, BILLDATE, 
      MAKEMAN, FLAGPOST, MEMO, STATUS, INOUTFLAG, OLDBILLCODE,EMPID,BUMENID
	FROM STOREQTRKM
	UNION
	SELECT BILLID, YYYYMM, BILLTYPE, VENDORID, CLIENTID, POSTMAN, CODE, BILLDATE, 
      MAKEMAN, FLAGPOST, MEMO, STATUS, INOUTFLAG, OLDBILLCODE,EMPID,BUMENID
	FROM STOREQTCKM
	UNION
	SELECT BILLID, YYYYMM, BILLTYPE, VENDORID, CLIENTID, POSTMAN, CODE, BILLDATE, 
      MAKEMAN, FLAGPOST, MEMO, STATUS, INOUTFLAG, OLDBILLCODE,EMPID,BUMENID
	FROM STORECKDBM
	UNION
	SELECT BILLID, YYYYMM, BILLTYPE, VENDORID, CLIENTID, POSTMAN, CODE, BILLDATE, 
      MAKEMAN, FLAGPOST, MEMO, STATUS, INOUTFLAG, OLDBILLCODE,EMPID,BUMENID
	FROM STORECKPDM
	UNION
	SELECT BILLID, YYYYMM, BILLTYPE, VENDORID, CLIENTID, POSTMAN, CODE, BILLDATE, 
      MAKEMAN, FLAGPOST, MEMO, STATUS, INOUTFLAG, OLDBILLCODE,EMPID,BUMENID
	FROM STOREQTSRM
	UNION
	SELECT BILLID, YYYYMM, BILLTYPE, VENDORID, CLIENTID, POSTMAN, CODE, BILLDATE, 
      MAKEMAN, FLAGPOST, MEMO, STATUS, INOUTFLAG, OLDBILLCODE,EMPID,BUMENID
	FROM STOREFYKZM
	UNION
	SELECT BILLID, YYYYMM, BILLTYPE, VENDORID, CLIENTID, POSTMAN, CODE, BILLDATE, 
      MAKEMAN, FLAGPOST, MEMO, STATUS, INOUTFLAG, OLDBILLCODE,EMPID,BUMENID
	FROM STOREMOVEM
	UNION
	SELECT BILLID, YYYYMM, BILLTYPE, VENDORID, CLIENTID, POSTMAN, CODE, BILLDATE, 
      MAKEMAN, FLAGPOST, MEMO, STATUS, INOUTFLAG, OLDBILLCODE,EMPID,BUMENID
	FROM STORECSHM
	UNION
	SELECT BILLID, YYYYMM, BILLTYPE, VENDORID, CLIENTID, POSTMAN, CODE, BILLDATE, 
      MAKEMAN, FLAGPOST, MEMO, STATUS, INOUTFLAG, OLDBILLCODE,EMPID,BUMENID
	FROM STORECGTHM
	UNION
	SELECT BILLID, YYYYMM, BILLTYPE, VENDORID, CLIENTID, POSTMAN, CODE, BILLDATE, 
      MAKEMAN, FLAGPOST, MEMO, STATUS, INOUTFLAG, OLDBILLCODE,EMPID,BUMENID
	FROM STOREXSTHM
	UNION
	SELECT BILLID, YYYYMM, BILLTYPE, VENDORID, CLIENTID, POSTMAN, CODE, BILLDATE, 
      MAKEMAN, FLAGPOST, MEMO, STATUS, INOUTFLAG, OLDBILLCODE,EMPID,BUMENID
	FROM STOREFYKZM
	UNION
	SELECT BILLID, YYYYMM, BILLTYPE, VENDORID, CLIENTID, POSTMAN, CODE, BILLDATE, 
      MAKEMAN, FLAGPOST, MEMO, STATUS, INOUTFLAG, OLDBILLCODE,EMPID,BUMENID
	FROM STOREGJRKM
	UNION
	SELECT BILLID, YYYYMM, BILLTYPE, VENDORID, CLIENTID, POSTMAN, CODE, BILLDATE, 
      MAKEMAN, FLAGPOST, MEMO, STATUS, INOUTFLAG, OLDBILLCODE,EMPID,BUMENID
	FROM STORELIUHM
	UNION
	SELECT BILLID, YYYYMM, BILLTYPE, VENDORID, CLIENTID, POSTMAN, CODE, BILLDATE, 
      MAKEMAN, FLAGPOST, MEMO, STATUS, INOUTFLAG, OLDBILLCODE,EMPID,BUMENID
	FROM STOREQGDM
	UNION
	SELECT BILLID, YYYYMM, BILLTYPE, VENDORID, CLIENTID, POSTMAN, CODE, BILLDATE, 
      MAKEMAN, FLAGPOST, MEMO, STATUS, INOUTFLAG, OLDBILLCODE,EMPID,BUMENID
	FROM STOREQGADM

	UNION
	SELECT BILLID, YYYYMM, BILLTYPE, VENDORID, CLIENTID, POSTMAN, CODE, BILLDATE, 
      MAKEMAN, FLAGPOST, MEMO, STATUS, INOUTFLAG, OLDBILLCODE,EMPID,BUMENID
	FROM STOREJGDM






































----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG







CREATE VIEW dbo.VIEWCGRKM
AS

SELECT * FROM dbo.STORECGRKM

union

SELECT * FROM dbo.STORECGTHM








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG







CREATE VIEW dbo.VIEWCGRKM_CGTHM
AS

select * from STORECGRKM

union

select * from STORECGTHM








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG
















CREATE VIEW dbo.VIEWCLIENT
AS

select CLIENTID,CODE,Name ,1 as CLIENTFlag,AREAID,CONTATOR,PHONE from CLIENT where NOT (CLIENTid='AAAAAAAA')

UNION

select VendorID as CLIENTID,Code,Name,0 as CLIENTFlag,AREAID,CONTATOR,PHONE  from Vendor where HeSuanFlag=1
















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG









CREATE VIEW dbo.VIEWCLIENTBILLFLOW
AS
SELECT ID, CLIENTID, YYYYMM, YYYYMMBILL, BILLDATE, BILLTYPE, BILLID, BILLCODE, 
      BAMOUNT, 0 as INAMOUNT,  INAMOUNT as OUTAMOUNT, EAMOUNT, CACULATEFLAG, INOUTFLAG,BuMenID
FROM dbo.CLIENTBILLFLOW

where INOUTFLAG = -1

Union

SELECT ID, CLIENTID, YYYYMM, YYYYMMBILL, BILLDATE, BILLTYPE, BILLID, BILLCODE, 
      BAMOUNT, INAMOUNT,  OUTAMOUNT, EAMOUNT, CACULATEFLAG, INOUTFLAG,BuMenID
FROM dbo.CLIENTBILLFLOW

where INOUTFLAG = 1













----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG





















CREATE VIEW dbo.VIEWCLIENTJSNO
AS
SELECT dbo.CLIENT.*, dbo.AREA.GOODSNOJS
FROM dbo.CLIENT INNER JOIN
      dbo.AREA ON dbo.CLIENT.AREAID = dbo.AREA.LCODE





















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG







CREATE VIEW dbo.VIEWClient2013
AS
SELECT dbo.CLIENT.*,Rtrim(dbo.CLIENT.Code)+substring('                ',1,16-len(Rtrim(dbo.CLIENT.Code)))+Rtrim(dbo.CLIENT.Name) as ClientCodeName
FROM dbo.CLIENT







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG



















CREATE VIEW dbo.VIEWGOODSJSNO
AS
SELECT dbo.GOODS.*, dbo.GOODSTYPE.GOODSNOJS
FROM dbo.GOODS INNER JOIN
      dbo.GOODSTYPE ON dbo.GOODS.LCODE = dbo.GOODSTYPE.LCODE


















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG




















CREATE VIEW dbo.VIEWGOODSTYPEGOODSTREE
AS
SELECT GOODSID AS LCODE, LCODE AS PREVNO, NAME, unit, code  AS LCODE00
FROM GOODS
UNION
SELECT LCODE, PREVNO, NAME, '合计' AS unit,LCODE AS LCOCE00
FROM GOODSTYPE

















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG















CREATE VIEW dbo.VIEWVENDOR
AS

select vendorID,CODE,Name ,1 as VendorFlag,AREAID,CONTATOR,PHONE from Vendor where NOT (Vendorid='AAAAAAAA')

UNION

select ClientID as vendorID,Code,Name,0 as VendorFlag,AREAID,CONTATOR,PHONE  from Client where HeSuanFlag=1















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG







CREATE VIEW dbo.VIEWXSCKM
AS

SELECT * FROM dbo.STOREXSCKM

union

SELECT * FROM dbo.STOREXSTHM








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG







CREATE VIEW dbo.VIEWXSCKM_XSTHM
AS

select * from STOREXSCKM

union

select * from STOREXSTHM








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

















CREATE VIEW dbo.VIEWXSCK_2011
AS
SELECT -dbo.DETAILBILLFLOW.INQTY*dbo.DETAILBILLFLOW.INOUTFlag AS quantity, dbo.VIEWXSCK.BILLID, 
      dbo.VIEWXSCK.YYYYMM, dbo.VIEWXSCK.BILLTYPE, dbo.VIEWXSCK.VENDORID, 
      dbo.VIEWXSCK.CLIENTID, dbo.VIEWXSCK.BUMENID, dbo.VIEWXSCK.EMPID, 
      dbo.VIEWXSCK.POSTMAN, dbo.VIEWXSCK.MAKEMAN, dbo.VIEWXSCK.BILLDATE, 
      dbo.VIEWXSCK.CODE, dbo.VIEWXSCK.UPDATETIME, dbo.VIEWXSCK.FLAGPOST, 
      dbo.VIEWXSCK.SFLAG, dbo.VIEWXSCK.MEMO, dbo.VIEWXSCK.STATUS, 
      dbo.VIEWXSCK.INOUTFLAG, dbo.VIEWXSCK.OLDBILLCODE, 
      dbo.VIEWXSCK.SUMQTY, dbo.VIEWXSCK.SUMAMT, 
      dbo.VIEWXSCK.REFERBILLCODE, dbo.VIEWXSCK.DISCAMT, 
      dbo.VIEWXSCK.invoiceFlag, dbo.VIEWXSCK.invoiceCode, 
      dbo.VIEWXSCK.invoiceDate, dbo.VIEWXSCK.PAYTYPEID, dbo.VIEWXSCK.BANKID, 
      dbo.VIEWXSCK.CARCODE, dbo.VIEWXSCK.ADDRESS, dbo.VIEWXSCK.ITEMNO, 
      dbo.VIEWXSCK.STOREID, dbo.VIEWXSCK.GOODSID, dbo.VIEWXSCK.APRICE, 
      dbo.VIEWXSCK.PRICE, dbo.VIEWXSCK.DETAILBILLFLOWID, 
      dbo.VIEWXSCK.REDETAILBILLFLOWID, dbo.VIEWXSCK.UNITPRICE, 
      dbo.VIEWXSCK.UNITQTY, dbo.VIEWXSCK.DISC, dbo.VIEWXSCK.AMT, 
      dbo.VIEWXSCK.TAXAMT, dbo.VIEWXSCK.PRICETYPE, dbo.VIEWXSCK.TAXRATE,

      dbo.VIEWXSCK.ClientFlag
FROM dbo.VIEWXSCK LEFT OUTER JOIN
      dbo.DETAILBILLFLOW ON 
      dbo.VIEWXSCK.DETAILBILLFLOWID = dbo.DETAILBILLFLOW.ID


















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG



CREATE VIEW dbo.VIEW_CW_BILLFLOW
AS
SELECT dbo.CW_BILLFLOW.*, dbo.ItemInfo.DCFlag
FROM dbo.CW_BILLFLOW INNER JOIN
      dbo.ItemInfo ON dbo.CW_BILLFLOW.ItemBM = dbo.ItemInfo.itembm



----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG


















CREATE VIEW dbo.VIEWvendorJSNO
AS
SELECT dbo.vendor.*, dbo.AREA.GOODSNOJS
FROM dbo.vendor INNER JOIN
      dbo.AREA ON dbo.vendor.AREAID = dbo.AREA.LCODE




















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG





















CREATE VIEW dbo.VIEWCGRK
AS
SELECT dbo.STORECGRKM.*, dbo.STORECGRKD.ITEMNO, dbo.STORECGRKD.STOREID, 
      dbo.STORECGRKD.GOODSID, dbo.STORECGRKD.APRICE, dbo.STORECGRKD.PRICE, 
      dbo.STORECGRKD.QUANTITY, 
      dbo.STORECGRKD.DETAILBILLFLOWID, 
      dbo.STORECGRKD.REDETAILBILLFLOWID,
      dbo.STORECGRKD.UNITPRICE,
      dbo.STORECGRKD.UNITQTY,
      dbo.STORECGRKD.DISC,
      dbo.STORECGRKD.TAXRATE,
      dbo.STORECGRKD.AMT,
      dbo.STORECGRKD.PRICETYPE,
      dbo.STORECGRKD.TAXAMT,
      dbo.STORECGRKD.ChanDi,
      dbo.STORECGRKD.FuZhuQTY,
      dbo.STORECGRKD.CaiZhi
FROM dbo.STORECGRKD INNER JOIN
      dbo.STORECGRKM ON dbo.STORECGRKD.BILLID = dbo.STORECGRKM.BILLID
WHERE FLAGPOST = 1 


UNION

SELECT dbo.STORECGTHM.*, dbo.STORECGTHD.ITEMNO, dbo.STORECGTHD.STOREID, 
      dbo.STORECGTHD.GOODSID, dbo.STORECGTHD.APRICE, dbo.STORECGTHD.PRICE, 
      -dbo.STORECGTHD.QUANTITY  AS  QUANTITY , 
      dbo.STORECGTHD.DETAILBILLFLOWID, 
      dbo.STORECGTHD.REDETAILBILLFLOWID,
      dbo.STORECGTHD.UNITPRICE,
      -dbo.STORECGTHD.UNITQTY  as UNITQTY,  
      dbo.STORECGTHD.DISC,
      dbo.STORECGTHD.TAXRATE,
      -dbo.STORECGTHD.AMT    as amt,
      dbo.STORECGTHD.PRICETYPE,
      -dbo.STORECGTHD.TAXAMT  as  TAXAMT,
      dbo.STORECGTHD.ChanDi,
      dbo.STORECGTHD.FuZhuQTY,
      dbo.STORECGTHD.CaiZhi
FROM dbo.STORECGTHD INNER JOIN
      dbo.STORECGTHM ON dbo.STORECGTHD.BILLID = dbo.STORECGTHM.BILLID
WHERE FLAGPOST = 1 




































----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG



















CREATE VIEW dbo.VIEWCKDB
AS
SELECT dbo.STORECKDBM.*, dbo.STORECKDBD.ITEMNO, dbo.STORECKDBM.ClientID as OUTSTOREID,dbo.STORECKDBM.VendorID as INSTOREID, 
      dbo.STORECKDBD.GOODSID, dbo.STORECKDBD.APRICE, dbo.STORECKDBD.PRICE, 
      dbo.STORECKDBD.QUANTITY, 
      dbo.STORECKDBD.DETAILBILLFLOWID, 
      dbo.STORECKDBD.REDETAILBILLFLOWID,
    dbo.STORECKDBD.UNITPRICE,
    dbo.STORECKDBD.UNITQTY,
    dbo.STORECKDBD.DISC,
    dbo.STORECKDBD.pricetype,
    dbo.STORECKDBD.AMT,
      dbo.STORECKDBD.TAXRATE,
      dbo.STORECKDBD.chandi,
      dbo.STORECKDBD.FuZhuQTY,
      dbo.STORECKDBD.caizhi
FROM dbo.STORECKDBD INNER JOIN
      dbo.STORECKDBM ON dbo.STORECKDBD.BILLID = dbo.STORECKDBM.BILLID
WHERE FLAGPOST = 1 

Union

SELECT dbo.STOREZCDM.*, dbo.STOREZCDD.ITEMNO, dbo.STOREZCDD.STOREID as OUTSTOREID,dbo.STOREZCDD.INSTOREID ,  
      dbo.STOREZCDD.GOODSID, dbo.STOREZCDD.APRICE, dbo.STOREZCDD.PRICE, 
      dbo.STOREZCDD.QUANTITY, 
      dbo.STOREZCDD.DETAILBILLFLOWID, 
      dbo.STOREZCDD.REDETAILBILLFLOWID,
    dbo.STOREZCDD.UNITPRICE,
    dbo.STOREZCDD.UNITQTY,
    dbo.STOREZCDD.DISC,
    dbo.STOREZCDD.pricetype,
    dbo.STOREZCDD.AMT,
      dbo.STOREZCDD.TAXRATE,
      dbo.STOREZCDD.chandi,
      dbo.STOREZCDD.FuZhuQTY,
      dbo.STOREZCDD.caizhi
FROM dbo.STOREZCDD INNER JOIN
      dbo.STOREZCDM ON dbo.STOREZCDD.BILLID = dbo.STOREZCDM.BILLID
WHERE FLAGPOST = 1 


































----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG


















CREATE VIEW dbo.VIEWCKPD
AS
SELECT dbo.STORECKPDM.*, dbo.STORECKPDD.ITEMNO, dbo.STORECKPDD.STOREID, 
      dbo.STORECKPDD.GOODSID, dbo.STORECKPDD.APRICE, dbo.STORECKPDD.PRICE, 
      dbo.STORECKPDD.QUANTITY, 
      dbo.STORECKPDD.DETAILBILLFLOWID, 
      dbo.STORECKPDD.REDETAILBILLFLOWID,
    dbo.STORECKPDD.UNITPRICE,
    dbo.STORECKPDD.UNITQTY,
    dbo.STORECKPDD.DISC,
    dbo.STORECKPDD.pricetype,
      dbo.STORECKPDD.TAXRATE,
      dbo.STORECKPDD.chandi,
      dbo.STORECKPDD.FuZhuQTY,
      dbo.STORECKPDD.caizhi
FROM dbo.STORECKPDD INNER JOIN
      dbo.STORECKPDM ON dbo.STORECKPDD.BILLID = dbo.STORECKPDM.BILLID
WHERE FLAGPOST = 1 
































----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG





















CREATE VIEW dbo.VIEWDETAILBILLFLOWJSNO
AS
SELECT dbo.DETAILBILLFLOW.*, dbo.VIEWGOODSJSNO.GOODSNOJS
FROM dbo.VIEWGOODSJSNO RIGHT OUTER JOIN
      dbo.DETAILBILLFLOW ON 
      dbo.VIEWGOODSJSNO.GOODSID = dbo.DETAILBILLFLOW.GOODSID


















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG



















CREATE VIEW dbo.VIEWFYKZ
AS
SELECT dbo.STOREFYKZM.*, dbo.STOREFYKZD.ITEMNO, dbo.STOREFYKZD.STOREID, 
      dbo.STOREFYKZD.QUANTITY, dbo.STOREFYKZD.DETAILBILLFLOWID, 
      dbo.STOREFYKZD.REDETAILBILLFLOWID, dbo.STOREFYKZD.TAXRATE, 
      dbo.STOREFYKZD.MEMO AS ZHAIYAO
FROM dbo.STOREFYKZD INNER JOIN
      dbo.STOREFYKZM ON 
      dbo.STOREFYKZD.BILLID = dbo.STOREFYKZM.BILLID
WHERE (dbo.STOREFYKZM.FLAGPOST = 1)





















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG















CREATE VIEW dbo.VIEWGJRK
AS
SELECT dbo.STOREGJRKM.*, dbo.STOREGJRKD.ITEMNO, dbo.STOREGJRKD.STOREID, 
      dbo.STOREGJRKD.GOODSID, dbo.STOREGJRKD.APRICE, dbo.STOREGJRKD.PRICE, 
      dbo.STOREGJRKD.QUANTITY, 
      dbo.STOREGJRKD.DETAILBILLFLOWID, 
      dbo.STOREGJRKD.REDETAILBILLFLOWID,
      dbo.STOREGJRKD.UNITPRICE,
      dbo.STOREGJRKD.UNITQTY,
      dbo.STOREGJRKD.DISC,
      dbo.STOREGJRKD.TAXRATE,
      dbo.STOREGJRKD.RETURNQTY
FROM dbo.STOREGJRKM LEFT OUTER JOIN
      dbo.STOREGJRKD ON 
      dbo.STOREGJRKM.BILLID = dbo.STOREGJRKD.BILLID 
WHERE FLAGPOST = 1 






















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG





CREATE VIEW dbo.VIEWGOODS_ZaiTu
AS
SELECT dbo.STORECGRKM.BILLID, dbo.STORECGRKM.FLAGPOST, 
      dbo.STORECGRKD.STOREID, dbo.STORECGRKD.GOODSID, 
      dbo.STORECGRKD.ITEMNO, dbo.STORECGRKD.QUANTITY, 
      dbo.STORECGRKD.UNITQTY
FROM dbo.STORECGRKM INNER JOIN
      dbo.STORECGRKD ON dbo.STORECGRKM.BILLID = dbo.STORECGRKD.BILLID
where  ISNULL(Flagpost,0)=0

union

SELECT dbo.STORECGTHM.BILLID, dbo.STORECGTHM.FLAGPOST, 
      dbo.STORECGTHD.STOREID, dbo.STORECGTHD.GOODSID, 
      dbo.STORECGTHD.ITEMNO,  -dbo.STORECGTHD.QUANTITY  as QUANTITY, 
      -dbo.STORECGTHD.UNITQTY  as UNITQTY
FROM dbo.STORECGTHM INNER JOIN
      dbo.STORECGTHD ON dbo.STORECGTHM.BILLID = dbo.STORECGTHD.BILLID
where  ISNULL(Flagpost,0)=0

union

SELECT dbo.STOREXSCKM.BILLID, dbo.STOREXSCKM.FLAGPOST, 
      dbo.STOREXSCKD.STOREID, dbo.STOREXSCKD.GOODSID, 
      dbo.STOREXSCKD.ITEMNO,  -dbo.STOREXSCKD.QUANTITY  as QUANTITY, 
      -dbo.STOREXSCKD.UNITQTY  as UNITQTY
FROM dbo.STOREXSCKM INNER JOIN
      dbo.STOREXSCKD ON dbo.STOREXSCKM.BILLID = dbo.STOREXSCKD.BILLID
where  ISNULL(Flagpost,0)=0

union

SELECT dbo.STOREXSTHM.BILLID, dbo.STOREXSTHM.FLAGPOST, 
      dbo.STOREXSTHD.STOREID, dbo.STOREXSTHD.GOODSID, 
      dbo.STOREXSTHD.ITEMNO, dbo.STOREXSTHD.QUANTITY, 
      dbo.STOREXSTHD.UNITQTY
FROM dbo.STOREXSTHM INNER JOIN
      dbo.STOREXSTHD ON dbo.STOREXSTHM.BILLID = dbo.STOREXSTHD.BILLID
where  ISNULL(Flagpost,0)=0


--------订单已经审核，但是未生成下游单据
union

SELECT dbo.STORECGDDM.BILLID, dbo.STORECGDDM.FLAGPOST, 
      dbo.STORECGDDD.STOREID, dbo.STORECGDDD.GOODSID, 
      dbo.STORECGDDD.ITEMNO, dbo.STORECGDDD.QUANTITY, 
      dbo.STORECGDDD.UNITQTY
FROM dbo.STORECGDDM INNER JOIN
      dbo.STORECGDDD ON dbo.STORECGDDM.BILLID = dbo.STORECGDDD.BILLID
where  ISNULL(Flagpost,0)=1 and ('CD'+SubString(STORECGDDD.BILLID,3,6) NOT IN (Select BILLID From STORECGRKM)) 


union

SELECT dbo.STOREXSDDM.BILLID, dbo.STOREXSDDM.FLAGPOST, 
      dbo.STOREXSDDD.STOREID, dbo.STOREXSDDD.GOODSID, 
      dbo.STOREXSDDD.ITEMNO, -dbo.STOREXSDDD.QUANTITY  as QUANTITY, 
      -dbo.STOREXSDDD.UNITQTY AS UNITQTY
FROM dbo.STOREXSDDM INNER JOIN
      dbo.STOREXSDDD ON dbo.STOREXSDDM.BILLID = dbo.STOREXSDDD.BILLID
where  ISNULL(Flagpost,0)=1 and ('XD'+SubString(STOREXSDDD.BILLID,3,6) NOT IN (Select BILLID From STOREXSCKM)) 


union

SELECT dbo.STOREQTRKM.BILLID, dbo.STOREQTRKM.FLAGPOST, 
      dbo.STOREQTRKD.STOREID, dbo.STOREQTRKD.GOODSID, 
      dbo.STOREQTRKD.ITEMNO, dbo.STOREQTRKD.QUANTITY, 
      dbo.STOREQTRKD.UNITQTY
FROM dbo.STOREQTRKM INNER JOIN
      dbo.STOREQTRKD ON dbo.STOREQTRKM.BILLID = dbo.STOREQTRKD.BILLID
where  ISNULL(Flagpost,0)=0

union

SELECT dbo.STOREQTCKM.BILLID, dbo.STOREQTCKM.FLAGPOST, 
      dbo.STOREQTCKD.STOREID, dbo.STOREQTCKD.GOODSID, 
      dbo.STOREQTCKD.ITEMNO,  -dbo.STOREQTCKD.QUANTITY  as QUANTITY, 
      -dbo.STOREQTCKD.UNITQTY  as UNITQTY
FROM dbo.STOREQTCKM INNER JOIN
      dbo.STOREQTCKD ON dbo.STOREQTCKM.BILLID = dbo.STOREQTCKD.BILLID
where  ISNULL(Flagpost,0)=0
union

SELECT dbo.STORECKDBM.BILLID, dbo.STORECKDBM.FLAGPOST, 
      dbo.STORECKDBM.ClientID as StoreID, dbo.STORECKDBD.GOODSID, 
      dbo.STORECKDBD.ITEMNO,  -dbo.STORECKDBD.QUANTITY  as QUANTITY, 
      -dbo.STORECKDBD.UNITQTY  as UNITQTY
FROM dbo.STORECKDBM INNER JOIN
      dbo.STORECKDBD ON dbo.STORECKDBM.BILLID = dbo.STORECKDBD.BILLID
where  ISNULL(Flagpost,0)=0


union

SELECT dbo.STORECKDBM.BILLID, dbo.STORECKDBM.FLAGPOST, 
      dbo.STORECKDBM.VendorID as STOREID, dbo.STORECKDBD.GOODSID, 
      dbo.STORECKDBD.ITEMNO, dbo.STORECKDBD.QUANTITY, 
      dbo.STORECKDBD.UNITQTY
FROM dbo.STORECKDBM INNER JOIN
      dbo.STORECKDBD ON dbo.STORECKDBM.BILLID = dbo.STORECKDBD.BILLID
where  ISNULL(Flagpost,0)=0

union

SELECT dbo.STOREQGDM.BILLID, dbo.STOREQGDM.FLAGPOST, 
      dbo.STOREQGDM.VendorID as STOREID, dbo.STOREQGDD.GOODSID, 
      dbo.STOREQGDD.ITEMNO, dbo.STOREQGDD.QUANTITY, 
      dbo.STOREQGDD.UNITQTY
FROM dbo.STOREQGDM INNER JOIN
      dbo.STOREQGDD ON dbo.STOREQGDM.BILLID = dbo.STOREQGDD.BILLID
where  ISNULL(Flagpost,0)=0

union

SELECT dbo.STOREQGDM.BILLID, dbo.STOREQGDM.FLAGPOST, 
      dbo.STOREQGDS.STOREID, dbo.STOREQGDS.GOODSID, 
      dbo.STOREQGDS.ITEMNO,  -dbo.STOREQGDS.QUANTITY  as QUANTITY, 
      -dbo.STOREQGDS.UNITQTY  as UNITQTY
FROM dbo.STOREQGDM INNER JOIN
      dbo.STOREQGDS ON dbo.STOREQGDM.BILLID = dbo.STOREQGDS.BILLID
where  ISNULL(Flagpost,0)=0

union

SELECT dbo.STOREJGDM.BILLID, dbo.STOREJGDM.FLAGPOST, 
      dbo.STOREJGDD.STOREID, dbo.STOREJGDD.GOODSID, 
      dbo.STOREJGDD.ITEMNO, dbo.STOREJGDD.QUANTITY, 
      dbo.STOREJGDD.UNITQTY
FROM dbo.STOREJGDM INNER JOIN
      dbo.STOREJGDD ON dbo.STOREJGDM.BILLID = dbo.STOREJGDD.BILLID
where  ISNULL(Flagpost,0)=0
union

SELECT dbo.STOREQGADM.BILLID, dbo.STOREQGADM.FLAGPOST, 
      dbo.STOREQGADD.STOREID, dbo.STOREQGADD.GOODSID, 
      dbo.STOREQGADD.ITEMNO, dbo.STOREQGADD.QUANTITY, 
      dbo.STOREQGADD.UNITQTY
FROM dbo.STOREQGADM INNER JOIN
      dbo.STOREQGADD ON dbo.STOREQGADM.BILLID = dbo.STOREQGADD.BILLID
where  ISNULL(Flagpost,0)=0
union

SELECT dbo.STOREQGADM.BILLID, dbo.STOREQGADM.FLAGPOST, 
      dbo.STOREQGADM.STOREID, dbo.STOREQGADM.GOODSID, 
      dbo.STOREQGADM.BILLID as ITEMNO,  -dbo.STOREQGADM.INVOICEAMT  as QUANTITY, 
      -dbo.STOREQGADM.SumQTY  as UNITQTY
FROM dbo.STOREQGADM 
where  ISNULL(Flagpost,0)=0



----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG


















CREATE VIEW dbo.VIEWQTCK
AS
SELECT dbo.STOREQTCKM.*, dbo.STOREQTCKD.ITEMNO, dbo.STOREQTCKD.STOREID, 
      dbo.STOREQTCKD.GOODSID, dbo.STOREQTCKD.APRICE, dbo.STOREQTCKD.PRICE, 
      dbo.STOREQTCKD.QUANTITY, 
      dbo.STOREQTCKD.DETAILBILLFLOWID, 
      dbo.STOREQTCKD.REDETAILBILLFLOWID,
    dbo.STOREQTCKD.UNITPRICE,
    dbo.STOREQTCKD.UNITQTY,
    dbo.STOREQTCKD.DISC,
    dbo.STOREQTCKD.pricetype,
    dbo.STOREQTCKD.AMT,
      dbo.STOREQTCKD.TAXRATE,
      dbo.STOREQTCKD.chandi,
      dbo.STOREQTCKD.FuZhuQTY,
      dbo.STOREQTCKD.caizhi
FROM dbo.STOREQTCKD INNER JOIN
      dbo.STOREQTCKM ON dbo.STOREQTCKD.BILLID = dbo.STOREQTCKM.BILLID
WHERE FLAGPOST = 1 
































----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG



















CREATE VIEW dbo.VIEWQTRK
AS
SELECT dbo.STOREQTRKM.*, dbo.STOREQTRKD.ITEMNO, dbo.STOREQTRKD.STOREID, 
      dbo.STOREQTRKD.GOODSID, dbo.STOREQTRKD.APRICE, dbo.STOREQTRKD.PRICE, 
      dbo.STOREQTRKD.QUANTITY, 
      dbo.STOREQTRKD.DETAILBILLFLOWID, 
      dbo.STOREQTRKD.REDETAILBILLFLOWID,
    dbo.STOREQTRKD.UNITPRICE,
    dbo.STOREQTRKD.UNITQTY,
    dbo.STOREQTRKD.DISC,
    dbo.STOREQTRKD.pricetype,
    dbo.STOREQTRKD.AMT,
      dbo.STOREQTRKD.TAXRATE,
      dbo.STOREQTRKD.chandi,
      dbo.STOREQTRKD.FuZhuQTY,
      dbo.STOREQTRKD.caizhi
FROM dbo.STOREQTRKD INNER JOIN
      dbo.STOREQTRKM ON dbo.STOREQTRKD.BILLID = dbo.STOREQTRKM.BILLID
WHERE FLAGPOST = 1 






























----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG




















CREATE VIEW dbo.VIEWQTSR
AS
SELECT dbo.STOREQTSRM.*, dbo.STOREQTSRD.ITEMNO, dbo.STOREQTSRD.STOREID, 
      dbo.STOREQTSRD.QUANTITY,
      dbo.STOREQTSRD.DETAILBILLFLOWID, 
      dbo.STOREQTSRD.REDETAILBILLFLOWID,
      dbo.STOREQTSRD.MEMO AS ZHAIYAO,
      dbo.STOREQTSRD.TAXRATE
FROM dbo.STOREQTSRD INNER JOIN
      dbo.STOREQTSRM ON dbo.STOREQTSRD.BILLID = dbo.STOREQTSRM.BILLID
WHERE FLAGPOST = 1 





























----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG











































CREATE VIEW dbo.VIEWXSCKGOODSCODE_2011
AS
SELECT dbo.VIEWXSCK_2011.*, dbo.GOODS.CODE AS GOODSCODE,dbo.GOODS.unit  AS UNIT
FROM dbo.VIEWXSCK_2011 LEFT OUTER JOIN
      dbo.GOODS ON dbo.VIEWXSCK_2011.GOODSID = dbo.GOODS.GOODSID






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG


CREATE VIEW dbo.VIEWXSCK_2014
AS
SELECT dbo.VIEWXSCKM_XSTHM.BILLID, dbo.VIEWXSCKM_XSTHM.YYYYMM, 
      dbo.VIEWXSCKM_XSTHM.CLIENTID, dbo.VIEWXSCKM_XSTHM.BUMENID, 
      dbo.VIEWXSCKM_XSTHM.EMPID, dbo.VIEWXSCKM_XSTHM.BILLDATE, 
      dbo.VIEWXSCKM_XSTHM.CODE, dbo.VIEWXSCKM_XSTHM.VendorHKSum, 
      dbo.VIEWXSCK_Sum.TaxAMT, dbo.VIEWXSCK_Sum.AMT, 
      dbo.VIEWXSCKM_XSTHM.ClientFlag, dbo.VIEWXSCKM_XSTHM.BILLTYPE
FROM dbo.VIEWXSCKM_XSTHM INNER JOIN
      dbo.VIEWXSCK_Sum ON 
      dbo.VIEWXSCKM_XSTHM.BILLID = dbo.VIEWXSCK_Sum.BILLID AND 
      dbo.VIEWXSCKM_XSTHM.BILLTYPE = dbo.VIEWXSCK_Sum.BILLType


----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG



CREATE VIEW dbo.VIEW_CW_PingZheng
AS
SELECT dbo.CW_PingZhengM.*, dbo.CW_PingZhengD.ItemBM, 
      dbo.CW_PingZhengD.debit, dbo.CW_PingZhengD.credit, 
      dbo.CW_PingZhengD.brief
FROM dbo.CW_PingZhengM INNER JOIN
      dbo.CW_PingZhengD ON dbo.CW_PingZhengM.BILLID = dbo.CW_PingZhengD.BILLID



----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG


CREATE VIEW [dbo].[ViewCGDD]
AS
SELECT     dbo.STORECGDDM.*, dbo.STORECGDDD.ITEMNO, dbo.STORECGDDD.STOREID, dbo.STORECGDDD.GOODSID, dbo.STORECGDDD.APRICE, dbo.STORECGDDD.PRICE,
                       dbo.STORECGDDD.QUANTITY, dbo.STORECGDDD.MEMO AS Expr1, dbo.STORECGDDD.DETAILBILLFLOWID, dbo.STORECGDDD.REDETAILBILLFLOWID, 
                      dbo.STORECGDDD.TAXRATE, dbo.STORECGDDD.DISC, dbo.STORECGDDD.UNITPRICE, dbo.STORECGDDD.UNITQTY, dbo.STORECGDDD.REGJRKCODE, 
                      dbo.STORECGDDD.REGJRKITEMNO, dbo.STORECGDDD.PRICETYPE, dbo.STORECGDDD.AMT, dbo.STORECGDDD.TAXAMT, dbo.STORECGDDD.YunFeiFT, 
                      dbo.STORECGDDD.CaiZhi, dbo.STORECGDDD.ChanDi, dbo.STORECGDDD.AMOUNT, dbo.STORECGDDD.invoiceqty, dbo.STORECGDDD.invoiceamt AS Expr2, 
                      dbo.STORECGDDD.InvoiceNow AS Expr3, dbo.STORECGDDD.SPECNameD, dbo.STORECGDDD.JianShu, dbo.STORECGDDD.MeiJianQty, dbo.STORECGDDD.LingTou, 
                      dbo.STORECGDDD.FuZhuQTY, dbo.STORECGDDD.ZongLen, dbo.STORECGDDD.WCUnitQty, dbo.STORECGDDD.WCQuantity, dbo.STORECGDDD.ZZUnitQty, 
                      dbo.STORECGDDD.ZZQuantity, dbo.STORECGDDD.DXSPrice, dbo.STORECGDDD.MXSPrice
FROM         dbo.STORECGDDM INNER JOIN
                      dbo.STORECGDDD ON dbo.STORECGDDM.BILLID = dbo.STORECGDDD.BILLID
                      WHERE FLAGPOST = 1 



----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG


CREATE VIEW [dbo].[ViewXSDD]
AS
SELECT     dbo.STOREXSDDM.*, dbo.STOREXSDDD.ITEMNO, dbo.STOREXSDDD.STOREID, dbo.STOREXSDDD.GOODSID, dbo.STOREXSDDD.APRICE, dbo.STOREXSDDD.PRICE, 
                      dbo.STOREXSDDD.QUANTITY, dbo.STOREXSDDD.MEMO AS Expr1, dbo.STOREXSDDD.DETAILBILLFLOWID, dbo.STOREXSDDD.REDETAILBILLFLOWID, 
                      dbo.STOREXSDDD.TAXRATE, dbo.STOREXSDDD.DISC, dbo.STOREXSDDD.UNITPRICE, dbo.STOREXSDDD.UNITQTY, dbo.STOREXSDDD.PRICETYPE, 
                      dbo.STOREXSDDD.AMT, dbo.STOREXSDDD.TAXAMT, dbo.STOREXSDDD.YunFeiFT, dbo.STOREXSDDD.CaiZhi, dbo.STOREXSDDD.ChanDi, 
                      dbo.STOREXSDDD.AMOUNT, dbo.STOREXSDDD.invoiceqty, dbo.STOREXSDDD.invoiceamt AS Expr2, dbo.STOREXSDDD.InvoiceNow AS Expr3, 
                      dbo.STOREXSDDD.SPECNameD, dbo.STOREXSDDD.JianShu, dbo.STOREXSDDD.MeiJianQty, dbo.STOREXSDDD.LingTou, dbo.STOREXSDDD.FuZhuQTY, 
                      dbo.STOREXSDDD.ZongLen, dbo.STOREXSDDD.WCunitQty, dbo.STOREXSDDD.WCquantity, dbo.STOREXSDDD.ZZunitQty, dbo.STOREXSDDD.ZZquantity, 
                      dbo.STOREXSDDD.DXSPrice, dbo.STOREXSDDD.MXSPrice
FROM         dbo.STOREXSDDM INNER JOIN
                      dbo.STOREXSDDD ON dbo.STOREXSDDM.BILLID = dbo.STOREXSDDD.BILLID
                      WHERE FLAGPOST = 1 


----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG





















CREATE VIEW dbo.VIEWCGRKGOODSCODE
AS
SELECT dbo.VIEWCGRK.*, dbo.GOODS.CODE AS GOODSCODE,dbo.GOODS.unit  AS UNIT
FROM dbo.VIEWCGRK LEFT OUTER JOIN
      dbo.GOODS ON dbo.VIEWCGRK.GOODSID = dbo.GOODS.GOODSID


































----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG



CREATE VIEW dbo.VIEWCGRK_Sum
AS
SELECT  BILLID,BILLDATE,BILLType,BumenID,Memo,EMPID,
sum(AMT) AS   AMT,sum(TaxAMT) as TaxAMT 
From VIEWCGRK
GROUP BY BILLID,BILLDATE,BILLType,BumenID,Memo,EMPID




----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG
























CREATE VIEW dbo.VIEWCKDBBILLJSNO
AS
SELECT dbo.VIEWCKDB.*, dbo.VIEWGOODSJSNO.GOODSNOJS
FROM dbo.VIEWCKDB LEFT OUTER JOIN
      dbo.VIEWGOODSJSNO ON 
      dbo.VIEWCKDB.GOODSID = dbo.VIEWGOODSJSNO.GOODSID



























----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG


















CREATE VIEW dbo.VIEWCKDBGOODSCODE
AS
SELECT dbo.VIEWCKDB.*, dbo.GOODS.CODE AS GOODSCODE
FROM dbo.VIEWCKDB LEFT OUTER JOIN
      dbo.GOODS ON dbo.VIEWCKDB.GOODSID = dbo.GOODS.GOODSID






















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG




















CREATE VIEW dbo.VIEWCKPDBILLJSNO
AS
SELECT dbo.VIEWCKPD.*, dbo.VIEWGOODSJSNO.GOODSNOJS
FROM dbo.VIEWCKPD LEFT OUTER JOIN
      dbo.VIEWGOODSJSNO ON 
      dbo.VIEWCKPD.GOODSID = dbo.VIEWGOODSJSNO.GOODSID




























----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG


















CREATE VIEW dbo.VIEWCKPDGOODSCODE
AS
SELECT dbo.VIEWCKPD.*, dbo.GOODS.CODE AS GOODSCODE
FROM dbo.VIEWCKPD LEFT OUTER JOIN
      dbo.GOODS ON dbo.VIEWCKPD.GOODSID = dbo.GOODS.GOODSID
























----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG



















CREATE VIEW dbo.VIEWFYKZJSNO
AS
SELECT dbo.VIEWFYKZ.*, dbo.OUTTYPE.GOODSNOJS
FROM dbo.VIEWFYKZ LEFT OUTER JOIN
      dbo.OUTTYPE ON 
      dbo.VIEWFYKZ.STOREID = dbo.OUTTYPE.LCODE






























----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

















CREATE VIEW dbo.VIEWGJRKGOODSCODE
AS
SELECT dbo.VIEWGJRK.*, dbo.GOODS.CODE AS GOODSCODE
FROM dbo.VIEWGJRK LEFT OUTER JOIN
      dbo.GOODS ON dbo.VIEWGJRK.GOODSID = dbo.GOODS.GOODSID

































----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG


















CREATE VIEW dbo.VIEWQTCKGOODSCODE
AS
SELECT dbo.VIEWQTCK.*, dbo.GOODS.CODE AS GOODSCODE
FROM dbo.VIEWQTCK LEFT OUTER JOIN
      dbo.GOODS ON dbo.VIEWQTCK.GOODSID = dbo.GOODS.GOODSID





























----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG



















CREATE VIEW dbo.VIEWQTRKGOODSCODE
AS
SELECT dbo.VIEWQTRK.*, dbo.GOODS.CODE AS GOODSCODE
FROM dbo.VIEWQTRK LEFT OUTER JOIN
      dbo.GOODS ON dbo.VIEWQTRK.GOODSID = dbo.GOODS.GOODSID



























----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG





















CREATE VIEW dbo.VIEWQTSRJSNO
AS
SELECT dbo.VIEWQTSR.*, dbo.INTYPE.GOODSNOJS
FROM dbo.VIEWQTSR LEFT OUTER JOIN
      dbo.INTYPE ON 
      dbo.VIEWQTSR.STOREID = dbo.INTYPE.LCODE





























----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG























CREATE VIEW dbo.VIEWXSCKGOODSCODE
AS
SELECT dbo.VIEWXSCK.*, dbo.GOODS.CODE AS GOODSCODE,dbo.GOODS.unit  AS UNIT
FROM dbo.VIEWXSCK LEFT OUTER JOIN
      dbo.GOODS ON dbo.VIEWXSCK.GOODSID = dbo.GOODS.GOODSID






































----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG












CREATE VIEW dbo.VIEWYunFeiMXB
AS
SELECT BILLTYPE, ChaCheSID as YunShuDWID,ChaCheSCarNO as CarNO, 
      ChaChePrice AS YunFeiPrice, YunFeiZhiFuFX, BILLID, CODE, BILLDATE, GOODSID,ClientID,VendorID, 
      QUANTITY,OLDBILLCODE
FROM dbo.VIEWCGRK
where (ChaCheSID is Not NULL) and  ISNULL(ChaChePrice,0)>=0   and YunFeiZhiFuFX='我方支付运费'

union

SELECT BILLTYPE, PanYunSID as YunShuDWID,PanYunSCarNO as CarNO, 
      PanYunPrice AS YunFeiPrice, YunFeiZhiFuFX, BILLID, CODE, BILLDATE, GOODSID,ClientID,VendorID,  
      QUANTITY,OLDBILLCODE
FROM dbo.VIEWCGRK
where (PanYunSID is Not NULL) and  ISNULL(PanYunPrice,0)>=0   and YunFeiZhiFuFX='我方支付运费'

union

SELECT BILLTYPE, ChaCheSID as YunShuDWID,ChaCheSCarNO as CarNO, 
      ChaChePrice AS YunFeiPrice, YunFeiZhiFuFX, BILLID, CODE, BILLDATE, GOODSID,ClientID,VendorID,  
      QUANTITY,OLDBILLCODE
FROM dbo.VIEWXSCK
where (ChaCheSID is Not NULL) and  ISNULL(ChaChePrice,0)>=0

union

SELECT BILLTYPE, PanYunSID as YunShuDWID,PanYunSCarNO as CarNO, 
      PanYunPrice AS YunFeiPrice, YunFeiZhiFuFX, BILLID, CODE, BILLDATE, GOODSID,ClientID,VendorID,  
      QUANTITY,OLDBILLCODE
FROM dbo.VIEWXSCK
where (PanYunSID is Not NULL) and  ISNULL(PanYunPrice,0)>=0
















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG



CREATE VIEW dbo.VIEW_CW_PingZheng_Code4
AS
SELECT dbo.VIEW_CW_PingZheng.*, SUBSTRING(ItemBM, 1, 4) AS itembmCode
FROM dbo.VIEW_CW_PingZheng



----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG



CREATE VIEW dbo.VIEWCGRK_2014
AS
SELECT dbo.VIEWCGRKM_CGTHM.BILLID, dbo.VIEWCGRKM_CGTHM.YYYYMM, 
      dbo.VIEWCGRKM_CGTHM.VendorID, dbo.VIEWCGRKM_CGTHM.BUMENID, 
      dbo.VIEWCGRKM_CGTHM.EMPID, dbo.VIEWCGRKM_CGTHM.BILLDATE, 
      dbo.VIEWCGRKM_CGTHM.CODE, dbo.VIEWCGRKM_CGTHM.VendorHKSum, 
      dbo.VIEWCGRK_Sum.TaxAMT, dbo.VIEWCGRK_Sum.AMT, 
      dbo.VIEWCGRKM_CGTHM.VendorFlag, dbo.VIEWCGRKM_CGTHM.BILLTYPE
FROM dbo.VIEWCGRKM_CGTHM INNER JOIN
      dbo.VIEWCGRK_Sum ON 
      dbo.VIEWCGRKM_CGTHM.BILLID = dbo.VIEWCGRK_Sum.BILLID AND 
      dbo.VIEWCGRKM_CGTHM.BILLTYPE = dbo.VIEWCGRK_Sum.BILLType



----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG
delete  FunctionM 
----------ENDFLAG

  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000001','00000001','APGCTXP','采购入库','FrmMain','N50','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000002','00000001','APGCTXP','新增单据','FormStoreDouble','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000003','00000001','APGCTXP','编辑单据','FormStoreDouble','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000004','00000001','APGCTXP','删除单据','FormStoreDouble','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000005','00000001','APGCTXP','单据记帐','FormStoreDouble','ToolButton1','J')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000006','00000001','APGCTXP','取消记帐','FormStoreDouble','ToolButton2','C')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000007','00000001','APGCTXP','打印','FormStoreDouble','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000008','00000001','APGCTXP','单据设置','FormStoreDouble','ToolButtonSETCOL','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000009','00000009','APGCTXP','采购退货','FrmMain','N168','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000010','00000009','APGCTXP','新增单据','FormCGTHBILL','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000011','00000009','APGCTXP','编辑单据','FormCGTHBILL','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000012','00000009','APGCTXP','删除单据','FormCGTHBILL','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000013','00000009','APGCTXP','单据记帐','FormCGTHBILL','ToolButton1','J')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000014','00000009','APGCTXP','取消记帐','FormCGTHBILL','ToolButton2','C')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000015','00000009','APGCTXP','打印','FormCGTHBILL','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000016','00000009','APGCTXP','单据设置','FormCGTHBILL','ToolButtonSETCOL','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000017','00000017','APGCTXP','销售退货','FrmMain','N169','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000018','00000017','APGCTXP','新增单据','FormXSTHBILL','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000019','00000017','APGCTXP','编辑单据','FormXSTHBILL','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000020','00000017','APGCTXP','删除单据','FormXSTHBILL','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000021','00000017','APGCTXP','单据记帐','FormXSTHBILL','ToolButton1','J')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000022','00000017','APGCTXP','取消记帐','FormXSTHBILL','ToolButton2','C')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000023','00000017','APGCTXP','打印','FormXSTHBILL','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000024','00000017','APGCTXP','单据设置','FormXSTHBILL','ToolButtonSETCOL','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000025','00000025','APGCTXP','其他入库','FrmMain','N53','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000026','00000025','APGCTXP','新增单据','FormQTRKBILL','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000027','00000025','APGCTXP','编辑单据','FormQTRKBILL','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000028','00000025','APGCTXP','删除单据','FormQTRKBILL','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000029','00000025','APGCTXP','单据记帐','FormQTRKBILL','ToolButton1','J')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000030','00000025','APGCTXP','取消记帐','FormQTRKBILL','ToolButton2','C')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000031','00000025','APGCTXP','打印','FormQTRKBILL','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000032','00000025','APGCTXP','单据设置','FormQTRKBILL','ToolButtonSETCOL','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000033','00000033','APGCTXP','仓库盘点单','FrmMain','N41','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000034','00000033','APGCTXP','新增单据','FormCKPDBILL','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000035','00000033','APGCTXP','编辑单据','FormCKPDBILL','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000036','00000033','APGCTXP','删除单据','FormCKPDBILL','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000037','00000033','APGCTXP','单据记帐','FormCKPDBILL','ToolButton1','J')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000038','00000033','APGCTXP','取消记帐','FormCKPDBILL','ToolButton2','C')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000039','00000033','APGCTXP','打印','FormCKPDBILL','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000040','00000033','APGCTXP','单据设置','FormCKPDBILL','ToolButtonSETCOL','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000041','00000041','APGCTXP','其他出库','FrmMain','N55','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000042','00000041','APGCTXP','新增单据','FormQTCKBILL','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000043','00000041','APGCTXP','编辑单据','FormQTCKBILL','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000044','00000041','APGCTXP','删除单据','FormQTCKBILL','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000045','00000041','APGCTXP','单据记帐','FormQTCKBILL','ToolButton1','J')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000046','00000041','APGCTXP','取消记帐','FormQTCKBILL','ToolButton2','C')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000047','00000041','APGCTXP','打印','FormQTCKBILL','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000048','00000041','APGCTXP','单据设置','FormQTCKBILL','ToolButtonSETCOL','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000049','00000049','APGCTXP','付款单','FrmMain','N51','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000050','00000049','APGCTXP','新增单据','FormCGFKBILL','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000051','00000049','APGCTXP','编辑单据','FormCGFKBILL','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000052','00000049','APGCTXP','删除单据','FormCGFKBILL','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000053','00000049','APGCTXP','单据记帐','FormCGFKBILL','ToolButton1','J')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000054','00000049','APGCTXP','取消记帐','FormCGFKBILL','ToolButton2','C')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000055','00000049','APGCTXP','打印','FormCGFKBILL','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000056','00000049','APGCTXP','打印格式','FormCGFKBILL','ToolButtonPrintStyle','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000057','00000057','APGCTXP','收款单','FrmMain','N81','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000058','00000057','APGCTXP','新增单据','FormXSSKBILL','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000059','00000057','APGCTXP','编辑单据','FormXSSKBILL','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000060','00000057','APGCTXP','删除单据','FormXSSKBILL','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000061','00000057','APGCTXP','单据记帐','FormXSSKBILL','ToolButton1','J')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000062','00000057','APGCTXP','取消记帐','FormXSSKBILL','ToolButton2','C')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000063','00000057','APGCTXP','打印','FormXSSKBILL','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000064','00000057','APGCTXP','打印格式','FormXSSKBILL','ToolButtonPrintStyle','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000065','00000065','APGCTXP','销售出库','FrmMain','N27','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000066','00000065','APGCTXP','新增单据','FormXSCKBILL','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000067','00000065','APGCTXP','编辑单据','FormXSCKBILL','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000068','00000065','APGCTXP','删除单据','FormXSCKBILL','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000069','00000065','APGCTXP','单据记帐','FormXSCKBILL','ToolButton1','J')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000070','00000065','APGCTXP','取消记帐','FormXSCKBILL','ToolButton2','C')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000071','00000065','APGCTXP','打印','FormXSCKBILL','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000072','00000065','APGCTXP','单据设置','FormXSCKBILL','ToolButtonSETCOL','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000073','00000073','APGCTXP','转仓单','FrmMain','N61','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000074','00000073','APGCTXP','新增单据','FormCKDBBILL','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000075','00000073','APGCTXP','编辑单据','FormCKDBBILL','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000076','00000073','APGCTXP','删除单据','FormCKDBBILL','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000077','00000073','APGCTXP','单据记帐','FormCKDBBILL','ToolButton1','J')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000078','00000073','APGCTXP','取消记帐','FormCKDBBILL','ToolButton2','C')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000079','00000073','APGCTXP','打印','FormCKDBBILL','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000080','00000073','APGCTXP','单据设置','FormCKDBBILL','ToolButtonSETCOL','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000081','00000081','APGCTXP','区域资料','FrmMain','N30','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000082','00000081','APGCTXP','新增','FormAREA','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000083','00000081','APGCTXP','修改','FormAREA','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000084','00000081','APGCTXP','删除','FormAREA','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000085','00000081','APGCTXP','打印','FormAREA','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000086','00000081','APGCTXP','打印格式','FormAREA','ToolButtonPrintStyle','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000087','00000081','APGCTXP','导出数据','FormAREA','ToolButtonDataTo','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000088','00000088','APGCTXP','供应商资料','FrmMain','N31','H')
----------ENDFLAG
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000089','00000088','APGCTXP','新增','FormVENDOR','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000090','00000088','APGCTXP','修改','FormVENDOR','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000091','00000088','APGCTXP','删除','FormVENDOR','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000092','00000088','APGCTXP','打印','FormVENDOR','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000093','00000088','APGCTXP','打印格式','FormVENDOR','ToolButtonPrintStyle','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000094','00000088','APGCTXP','导出数据','FormVENDOR','ToolButtonDataTo','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000095','00000095','APGCTXP','客户资料','FrmMain','N32','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000096','00000095','APGCTXP','新增','FormClient','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000097','00000095','APGCTXP','修改','FormClient','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000098','00000095','APGCTXP','删除','FormClient','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000099','00000095','APGCTXP','打印','FormClient','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000100','00000095','APGCTXP','打印格式','FormClient','ToolButtonPrintStyle','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000101','00000095','APGCTXP','导出数据','FormClient','ToolButtonDataTo','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000102','00000102','APGCTXP','钢材类别资料','FrmMain','N13','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000103','00000102','APGCTXP','新增','FormGoodsType','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000104','00000102','APGCTXP','修改','FormGoodsType','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000105','00000102','APGCTXP','删除','FormGoodsType','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000108','00000102','APGCTXP','导出数据','FormGoodsType','ToolButtonDataTo','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000109','00000109','APGCTXP','计量单位','FrmMain','N24','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000110','00000109','APGCTXP','新增','FormUNIT','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000111','00000109','APGCTXP','修改','FormUNIT','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000112','00000109','APGCTXP','删除','FormUNIT','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000113','00000109','APGCTXP','打印','FormUNIT','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000114','00000109','APGCTXP','打印格式','FormUNIT','ToolButtonPrintStyle','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000115','00000109','APGCTXP','导出数据','FormUNIT','ToolButtonDataTo','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000116','00000116','APGCTXP','钢材档案资料','FrmMain','N23','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000117','00000116','APGCTXP','新增','FormGOODS','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000118','00000116','APGCTXP','修改','FormGOODS','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000119','00000116','APGCTXP','删除','FormGOODS','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000120','00000116','APGCTXP','打印','FormGOODS','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000121','00000116','APGCTXP','打印格式','FormGOODS','ToolButtonPrintStyle','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000122','00000116','APGCTXP','导出数据','FormGOODS','ToolButtonDataTo','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000123','00000123','APGCTXP','仓库资料','FrmMain','N10','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000124','00000123','APGCTXP','新增','FormSTORE','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000125','00000123','APGCTXP','修改','FormSTORE','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000126','00000123','APGCTXP','删除','FormSTORE','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000127','00000123','APGCTXP','打印','FormSTORE','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000128','00000123','APGCTXP','打印格式','FormSTORE','ToolButtonPrintStyle','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000129','00000123','APGCTXP','导出数据','FormSTORE','ToolButtonDataTo','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000144','00000144','APGCTXP','部门资料','FrmMain','N35','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000145','00000144','APGCTXP','新增','FormBUMEN','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000146','00000144','APGCTXP','修改','FormBUMEN','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000147','00000144','APGCTXP','删除','FormBUMEN','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000148','00000144','APGCTXP','打印','FormBUMEN','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000149','00000144','APGCTXP','打印格式','FormBUMEN','ToolButtonPrintStyle','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000150','00000144','APGCTXP','导出数据','FormBUMEN','ToolButtonDataTo','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000151','00000151','APGCTXP','员工类型','FrmMain','N39','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000152','00000151','APGCTXP','新增','FormEMPTYPE','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000153','00000151','APGCTXP','修改','FormEMPTYPE','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000154','00000151','APGCTXP','删除','FormEMPTYPE','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000157','00000151','APGCTXP','导出数据','FormEMPTYPE','ToolButtonDataTo','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000158','00000158','APGCTXP','员工资料','FrmMain','N34','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000159','00000158','APGCTXP','新增','FormEMPLOY','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000160','00000158','APGCTXP','修改','FormEMPLOY','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000161','00000158','APGCTXP','删除','FormEMPLOY','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000162','00000158','APGCTXP','打印','FormEMPLOY','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000163','00000158','APGCTXP','打印格式','FormEMPLOY','ToolButtonPrintStyle','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000164','00000158','APGCTXP','导出数据','FormEMPLOY','ToolButtonDataTo','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000165','00000165','APGCTXP','库存初始化','FrmMain','N22','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000166','00000165','APGCTXP','新增单据','FormCSHBILL','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000167','00000165','APGCTXP','编辑单据','FormCSHBILL','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000168','00000165','APGCTXP','删除单据','FormCSHBILL','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000169','00000165','APGCTXP','单据记帐','FormCSHBILL','ToolButton1','J')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000170','00000165','APGCTXP','取消记帐','FormCSHBILL','ToolButton2','C')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000171','00000165','APGCTXP','打印','FormCSHBILL','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000172','00000165','APGCTXP','单据设置','FormCSHBILL','ToolButtonSETCOL','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000177','00000177','APGCTXP','入库单汇总表','FrmMain','N5','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000179','00000179','APGCTXP','入库单明细表','FrmMain','N77','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000180','00000180','APGCTXP','出库单汇总表','FrmMain','N63','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000183','00000183','APGCTXP','转仓单汇总表','FrmMain','N66','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000185','00000185','APGCTXP','转仓单明细表','FrmMain','N80','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000186','00000186','APGCTXP','盘点开单汇总表','FrmMain','N67','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000188','00000188','APGCTXP','盘点开单明细表','FrmMain','N82','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000189','00000189','APGCTXP','库存汇总表','FrmMain','N83','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000190','00000190','APGCTXP','库存明细表','FrmMain','N84','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000192','00000192','APGCTXP','商品货位报表','FrmMain','N129','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000196','00000196','APGCTXP','当前库存余额','FrmMain','N4','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000198','00000198','APGCTXP','库存报警查询','FrmMain','N3','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000199','00000189','APGCTXP','打印','FormSTOREHZB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000200','00000189','APGCTXP','打印格式','FormSTOREHZB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000201','00000189','APGCTXP','导出数据','FormSTOREHZB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000202','00000190','APGCTXP','打印','FormSTOREMXB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000203','00000190','APGCTXP','打印格式','FormSTOREMXB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000204','00000190','APGCTXP','导出数据','FormSTOREMXB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000205','00000190','APGCTXP','单据','FormSTOREMXB','ToolButton4','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000214','00000177','APGCTXP','打印','FormRKHZTJB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000215','00000177','APGCTXP','打印格式','FormRKHZTJB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000216','00000177','APGCTXP','导出数据','FormRKHZTJB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000221','00000179','APGCTXP','打印','FormRKMXB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000222','00000179','APGCTXP','打印格式','FormRKMXB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000223','00000179','APGCTXP','导出数据','FormRKMXB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000224','00000180','APGCTXP','打印','FormCKHZTJB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000225','00000180','APGCTXP','打印格式','FormCKHZTJB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000226','00000180','APGCTXP','导出数据','FormCKHZTJB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000233','00000183','APGCTXP','打印','FormDBHZTJB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000234','00000183','APGCTXP','打印格式','FormDBHZTJB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000235','00000183','APGCTXP','导出数据','FormDBHZTJB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000239','00000185','APGCTXP','打印','FormDBMXB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000241','00000185','APGCTXP','打印格式','FormDBMXB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000242','00000185','APGCTXP','导出数据','FormDBMXB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000243','00000186','APGCTXP','打印','FormPDHZTJB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000244','00000186','APGCTXP','打印格式','FormPDHZTJB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000245','00000186','APGCTXP','导出数据','FormPDHZTJB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000249','00000188','APGCTXP','打印','FormPDMXB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000250','00000188','APGCTXP','打印格式','FormPDMXB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000251','00000188','APGCTXP','导出数据','FormPDMXB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000260','00000196','APGCTXP','打印','FormSTORELEDGER','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000261','00000196','APGCTXP','打印格式','FormSTORELEDGER','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000262','00000196','APGCTXP','导出数据','FormSTORELEDGER','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000266','00000266','APGCTXP','供应商供货汇总表','FrmMain','N116','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000267','00000266','APGCTXP','打印','FormVENDORCGRKHZTJB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000268','00000266','APGCTXP','打印格式','FormVENDORCGRKHZTJB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000269','00000266','APGCTXP','导出数据','FormVENDORCGRKHZTJB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000270','00000270','APGCTXP','供应商供货明细表','FrmMain','N117','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000271','00000270','APGCTXP','打印','FormVENDORCGRKMXB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000272','00000272','APGCTXP','估价入库货品汇总表','FrmMain','N122','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000273','00000270','APGCTXP','打印格式','FormVENDORCGRKMXB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000274','00000272','APGCTXP','打印','FORMGOODSGJRKYYYYMMDD','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000275','00000272','APGCTXP','打印格式','FORMGOODSGJRKYYYYMMDD','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000276','00000272','APGCTXP','导出数据','FORMGOODSGJRKYYYYMMDD','ToolButton3','D')
----------ENDFLAG
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000277','00000277','APGCTXP','估价入库货品明细表','FrmMain','N123','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000278','00000270','APGCTXP','导出数据','FormVENDORCGRKMXB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000279','00000279','APGCTXP','供应商估价入库汇总表','FrmMain','N124','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000280','00000279','APGCTXP','打印','FormVENDORGJRKHZB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000281','00000279','APGCTXP','打印格式','FormVENDORGJRKHZB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000282','00000282','APGCTXP','数据备份','FrmMain','N37','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000284','00000284','APGCTXP','其它收入单','FrmMain','N146','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000285','00000284','APGCTXP','新增单据','FormStoreDouble2005','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000286','00000284','APGCTXP','编辑单据','FormStoreDouble2005','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000287','00000284','APGCTXP','删除单据','FormStoreDouble2005','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000288','00000284','APGCTXP','单据记帐','FormStoreDouble2005','ToolButton1','J')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000289','00000284','APGCTXP','取消记帐','FormStoreDouble2005','ToolButton2','C')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000290','00000284','APGCTXP','打印','FormStoreDouble2005','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000291','00000284','APGCTXP','打印格式','FormStoreDouble2005','ToolButtonPrintStyle','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000292','00000292','APGCTXP','费用开支单','FrmMain','N147','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000293','00000292','APGCTXP','新增单据','FormStoreFYKZBILL','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000294','00000292','APGCTXP','编辑单据','FormStoreFYKZBILL','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000295','00000292','APGCTXP','删除单据','FormStoreFYKZBILL','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000296','00000292','APGCTXP','单据记帐','FormStoreFYKZBILL','ToolButton1','J')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000297','00000292','APGCTXP','取消记帐','FormStoreFYKZBILL','ToolButton2','C')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000298','00000292','APGCTXP','打印','FormStoreFYKZBILL','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000299','00000292','APGCTXP','打印格式','FormStoreFYKZBILL','ToolButtonPrintStyle','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000300','00000300','APGCTXP','银行存取款单','FrmMain','N145','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000301','00000300','APGCTXP','新增单据','FormMOVEBILL','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000302','00000300','APGCTXP','编辑单据','FormMOVEBILL','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000303','00000300','APGCTXP','删除单据','FormMOVEBILL','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000304','00000300','APGCTXP','单据记帐','FormMOVEBILL','ToolButton1','J')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000305','00000300','APGCTXP','取消记帐','FormMOVEBILL','ToolButton2','C')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000306','00000300','APGCTXP','打印','FormMOVEBILL','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000307','00000300','APGCTXP','打印格式','FormMOVEBILL','ToolButtonPrintStyle','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000308','00000277','APGCTXP','打印','FormGOODSGJRKMXB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000309','00000277','APGCTXP','打印格式','FormGOODSGJRKMXB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000310','00000277','APGCTXP','导出数据','FormGOODSGJRKMXB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000311','00000311','APGCTXP','商品采购汇总表','FrmMain','N102','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000312','00000311','APGCTXP','打印','FormStoreDoubleHZTJB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000313','00000311','APGCTXP','打印格式','FormStoreDoubleHZTJB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000314','00000311','APGCTXP','导出数据','FormStoreDoubleHZTJB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000315','00000315','APGCTXP','商品采购明细表','FrmMain','N104','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000316','00000315','APGCTXP','打印','FormStoreDoubleMXB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000317','00000315','APGCTXP','打印格式','FormStoreDoubleMXB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000318','00000315','APGCTXP','导出数据','FormStoreDoubleMXB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000319','00000319','APGCTXP','在估入库一缆表','FrmMain','N203','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000320','00000319','APGCTXP','打印','FormZGRKYLB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000321','00000319','APGCTXP','打印格式','FormZGRKYLB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000322','00000319','APGCTXP','导出数据','FormZGRKYLB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000323','00000323','APGCTXP','供应商估价入库明细表','FrmMain','N202','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000324','00000323','APGCTXP','打印','FormVENDORGJRKMXB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000325','00000323','APGCTXP','打印格式','FormVENDORGJRKMXB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000326','00000323','APGCTXP','导出数据','FormVENDORGJRKMXB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000327','00000327','APGCTXP','客户销售汇总表','FrmMain','N119','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000328','00000327','APGCTXP','打印','FormCLIENTXSCKHZTJB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000329','00000327','APGCTXP','打印格式','FormCLIENTXSCKHZTJB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000330','00000327','APGCTXP','导出数据','FormCLIENTXSCKHZTJB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000331','00000331','APGCTXP','客户销售明细表','FrmMain','N120','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000332','00000331','APGCTXP','打印','FormCLIENTXSCKMXB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000333','00000331','APGCTXP','打印格式','FormCLIENTXSCKMXB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000334','00000331','APGCTXP','导出数据','FormCLIENTXSCKMXB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000335','00000335','APGCTXP','商品销售汇总表','FrmMain','N105','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000336','00000335','APGCTXP','打印','FormXSCKBILLHZTJB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000337','00000335','APGCTXP','打印格式','FormXSCKBILLHZTJB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000338','00000335','APGCTXP','导出数据','FormXSCKBILLHZTJB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000339','00000339','APGCTXP','商品销售明细表','FrmMain','N107','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000340','00000339','APGCTXP','打印','FormXSCKBILLMXB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000341','00000339','APGCTXP','打印格式','FormXSCKBILLMXB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000342','00000339','APGCTXP','导出数据','FormXSCKBILLMXB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000343','00000343','APGCTXP','出库单明细表','FrmMain','N79','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000344','00000343','APGCTXP','打印','FormCKMXB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000345','00000343','APGCTXP','打印格式','FormCKMXB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000346','00000343','APGCTXP','导出数据','FormCKMXB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000351','00000351','APGCTXP','销售毛利汇总表(按客户)','FrmMain','N133','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000352','00000351','APGCTXP','打印','FormCLIENTXSCKMLR','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000353','00000351','APGCTXP','打印格式','FormCLIENTXSCKMLR','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000354','00000351','APGCTXP','导出数据','FormCLIENTXSCKMLR','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000355','00000355','APGCTXP','销售毛利汇总表(按商品)','FrmMain','N128','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000356','00000355','APGCTXP','打印','FormXSCKBILLMLRHZB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000357','00000355','APGCTXP','打印格式','FormXSCKBILLMLRHZB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000358','00000355','APGCTXP','导出数据','FormXSCKBILLMLRHZB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000359','00000359','APGCTXP','销售毛利明细表','FrmMain','N134','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000360','00000359','APGCTXP','打印','FormGOODSXSCKMLRMXB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000361','00000359','APGCTXP','打印格式','FormGOODSXSCKMLRMXB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000362','00000359','APGCTXP','导出数据','FormGOODSXSCKMLRMXB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000363','00000363','APGCTXP','销售按单毛利计算','FrmMain','N136','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000364','00000363','APGCTXP','打印','FormXSCKBILLMLR','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000365','00000363','APGCTXP','打印格式','FormXSCKBILLMLR','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000366','00000363','APGCTXP','导出数据','FormXSCKBILLMLR','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000367','00000367','APGCTXP','应收帐款汇总表','FrmMain','N45','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000368','00000367','APGCTXP','打印','FormCLIENTYYYYMMDD','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000369','00000367','APGCTXP','打印格式','FormCLIENTYYYYMMDD','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000370','00000367','APGCTXP','导出数据','FormCLIENTYYYYMMDD','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000371','00000371','APGCTXP','应收帐款明细表','FrmMain','N44','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000372','00000371','APGCTXP','打印','FormCLIENTINOUTMXBREP','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000373','00000371','APGCTXP','打印格式','FormCLIENTINOUTMXBREP','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000374','00000371','APGCTXP','导出数据','FormCLIENTINOUTMXBREP','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000375','00000375','APGCTXP','应付帐款汇总表','FrmMain','N47','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000376','00000375','APGCTXP','打印','FormVENDORYYYYMMDD','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000377','00000375','APGCTXP','打印格式','FormVENDORYYYYMMDD','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000378','00000375','APGCTXP','导出数据','FormVENDORYYYYMMDD','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000379','00000379','APGCTXP','应付帐款明细表','FrmMain','N57','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000380','00000379','APGCTXP','打印','FormVENDORINOUTMXBREP','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000381','00000379','APGCTXP','打印格式','FormVENDORINOUTMXBREP','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000382','00000379','APGCTXP','导出数据','FormVENDORINOUTMXBREP','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000383','00000383','APGCTXP','现金银行汇总表','FrmMain','N150','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000384','00000383','APGCTXP','打印','FormBANKYYYYMMDD','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000385','00000383','APGCTXP','打印格式','FormBANKYYYYMMDD','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000386','00000383','APGCTXP','导出数据','FormBANKYYYYMMDD','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000387','00000387','APGCTXP','现金银行明细表','FrmMain','N149','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000388','00000387','APGCTXP','打印','FormBANKINOUTMXBREP','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000389','00000387','APGCTXP','打印格式','FormBANKINOUTMXBREP','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000390','00000387','APGCTXP','导出数据','FormBANKINOUTMXBREP','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000391','00000391','APGCTXP','其他收入汇总表','FrmMain','N152','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000392','00000391','APGCTXP','打印','FormQTSRBILLTREE','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000393','00000391','APGCTXP','打印格式','FormQTSRBILLTREE','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000394','00000391','APGCTXP','导出数据','FormQTSRBILLTREE','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000395','00000395','APGCTXP','其他收入明细表','FrmMain','N153','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000396','00000395','APGCTXP','打印','FormQTSRMXB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000397','00000395','APGCTXP','打印格式','FormQTSRMXB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000398','00000395','APGCTXP','导出数据','FormQTSRMXB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000399','00000399','APGCTXP','费用开支汇总表','FrmMain','N155','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000400','00000399','APGCTXP','打印','FormFYKZBILLTREE','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000401','00000399','APGCTXP','打印格式','FormFYKZBILLTREE','ToolButton2','X')
----------ENDFLAG
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000402','00000399','APGCTXP','导出数据','FormFYKZBILLTREE','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000403','00000403','APGCTXP','费用开支明细表','FrmMain','N156','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000404','00000403','APGCTXP','打印','FormFYKZMXB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000405','00000403','APGCTXP','打印格式','FormFYKZMXB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000406','00000403','APGCTXP','导出数据','FormFYKZMXB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000423','00000423','APGCTXP','收入类别资料','FrmMain','N142','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000424','00000423','APGCTXP','新增','FormINTYPE','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000425','00000423','APGCTXP','修改','FormINTYPE','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000426','00000423','APGCTXP','删除','FormINTYPE','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000427','00000423','APGCTXP','打印','FormINTYPE','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000428','00000423','APGCTXP','打印格式','FormINTYPE','ToolButtonPrintStyle','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000429','00000423','APGCTXP','导出数据','FormINTYPE','ToolButtonDataTo','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000430','00000430','APGCTXP','支出类别资料','FrmMain','N143','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000431','00000430','APGCTXP','新增','FormOUTTYPE','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000432','00000430','APGCTXP','修改','FormOUTTYPE','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000433','00000430','APGCTXP','删除','FormOUTTYPE','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000434','00000430','APGCTXP','打印','FormOUTTYPE','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000435','00000430','APGCTXP','打印格式','FormOUTTYPE','ToolButtonPrintStyle','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000436','00000430','APGCTXP','导出数据','FormOUTTYPE','ToolButtonDataTo','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000437','00000437','APGCTXP','收付款方式','FrmMain','N141','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000438','00000437','APGCTXP','新增','FormPAYTYPE','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000439','00000437','APGCTXP','修改','FormPAYTYPE','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000440','00000437','APGCTXP','删除','FormPAYTYPE','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000441','00000437','APGCTXP','打印','FormPAYTYPE','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000442','00000437','APGCTXP','打印格式','FormPAYTYPE','ToolButtonPrintStyle','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000443','00000437','APGCTXP','导出数据','FormPAYTYPE','ToolButtonDataTo','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000444','00000444','APGCTXP','现金银行资料','FrmMain','N140','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000445','00000444','APGCTXP','新增','FormBANK','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000446','00000444','APGCTXP','修改','FormBANK','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000447','00000444','APGCTXP','删除','FormBANK','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000448','00000444','APGCTXP','打印','FormBANK','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000449','00000444','APGCTXP','打印格式','FormBANK','ToolButtonPrintStyle','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000450','00000444','APGCTXP','导出数据','FormBANK','ToolButtonDataTo','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000452','00000452','APGCTXP','单据记帐顺序表','FrmMain','N171','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000469','00000469','APGCTXP','估价入库','FrmMain','N191','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000470','00000469','APGCTXP','新增单据','FormGJRKBILL','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000471','00000469','APGCTXP','编辑单据','FormGJRKBILL','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000472','00000469','APGCTXP','删除单据','FormGJRKBILL','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000473','00000469','APGCTXP','单据记帐','FormGJRKBILL','ToolButton1','J')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000474','00000469','APGCTXP','取消记帐','FormGJRKBILL','ToolButton2','C')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000475','00000469','APGCTXP','打印','FormGJRKBILL','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000476','00000469','APGCTXP','单据设置','FormGJRKBILL','ToolButtonSETCOL','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000502','00000502','APGCTXP','销售日报表','FrmMain','N36','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000503','00000503','APGCTXP','销售月报表','FrmMain','N56','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000504','00000502','APGCTXP','打印','FormXSCKDayBB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000505','00000502','APGCTXP','打印格式','FormXSCKDayBB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000506','00000502','APGCTXP','导出数据','FormXSCKDayBB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000507','00000503','APGCTXP','打印','FormXSCKMonthBB','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000508','00000503','APGCTXP','打印格式','FormXSCKMonthBB','ToolButton2','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000509','00000503','APGCTXP','导出数据','FormXSCKMonthBB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000510','00000510','APGCTXP','运输单位应付帐款汇总表','FrmMain','N62','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000511','00000511','APGCTXP','运输单位应付帐款明细帐','FrmMain','N68','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000512','00000512','APGCTXP','运输清单报表','FrmMain','N72','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000513','00000513','APGCTXP','运费付款单','FrmMain','N69','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000514','00000513','APGCTXP','新增单据','FormYunFeiFKBILL','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000515','00000513','APGCTXP','编辑单据','FormYunFeiFKBILL','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000516','00000513','APGCTXP','删除单据','FormYunFeiFKBILL','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000517','00000513','APGCTXP','单据记帐','FormYunFeiFKBILL','ToolButton1','J')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000518','00000513','APGCTXP','取消记帐','FormYunFeiFKBILL','ToolButton2','C')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000519','00000513','APGCTXP','打印','FormYunFeiFKBILL','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000520','00000513','APGCTXP','打印格式','FormYunFeiFKBILL','ToolButtonPrintStyle','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000521','00000521','APGCTXP','运输单位','FrmMain','N58','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000522','00000521','APGCTXP','新增','FormYunShuDW','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000523','00000521','APGCTXP','修改','FormYunShuDW','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000524','00000521','APGCTXP','删除','FormYunShuDW','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000525','00000521','APGCTXP','打印','FormYunShuDW','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000526','00000521','APGCTXP','打印格式','FormYunShuDW','ToolButtonPrintStyle','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000527','00000521','APGCTXP','导出数据','FormYunShuDW','ToolButtonDataTo','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000528','00000528','APGCTXP','销售订单','FrmMain','N115','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000529','00000528','APGCTXP','新增单据','FormXSDDBILL','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000530','00000528','APGCTXP','编辑单据','FormXSDDBILL','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000531','00000528','APGCTXP','删除单据','FormXSDDBILL','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000533','00000528','APGCTXP','单据记帐','FormXSDDBILL','ToolButton1','J')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000534','00000528','APGCTXP','取消记帐','FormXSDDBILL','ToolButton2','C')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000535','00000528','APGCTXP','打印','FormXSDDBILL','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000536','00000528','APGCTXP','单据设置','FormXSDDBILL','ToolButtonSETCOL','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000537','00000537','APGCTXP','采购订单','FrmMain','N114','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000538','00000537','APGCTXP','新增单据','FormCGDDBILL','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000539','00000537','APGCTXP','编辑单据','FormCGDDBILL','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000540','00000537','APGCTXP','删除单据','FormCGDDBILL','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000541','00000537','APGCTXP','单据记帐','FormCGDDBILL','ToolButton1','J')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000542','00000537','APGCTXP','取消记帐','FormCGDDBILL','ToolButton2','C')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000543','00000537','APGCTXP','打印','FormCGDDBILL','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000544','00000537','APGCTXP','单据设置','FormCGDDBILL','ToolButtonSETCOL','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000547','00000547','APGCTXP','加工单','FrmMain','N163','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000548','00000547','APGCTXP','新增单据','FormJGDBILL','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000549','00000547','APGCTXP','编辑单据','FormJGDBILL','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000550','00000547','APGCTXP','删除单据','FormJGDBILL','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000551','00000547','APGCTXP','单据记帐','FormJGDBILL','ToolButton1','J')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000552','00000547','APGCTXP','取消记帐','FormJGDBILL','ToolButton2','C')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000553','00000547','APGCTXP','打印','FormJGDBILL','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000554','00000547','APGCTXP','单据设置','FormJGDBILL','ToolButtonSETCOL','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000555','00000555','APGCTXP','切割单','FrmMain','N164','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000556','00000555','APGCTXP','新增单据','FormQGDBILL','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000557','00000555','APGCTXP','编辑单据','FormQGDBILL','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000558','00000555','APGCTXP','删除单据','FormQGDBILL','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000559','00000555','APGCTXP','单据记帐','FormQGDBILL','ToolButton1','J')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000560','00000555','APGCTXP','取消记帐','FormQGDBILL','ToolButton2','C')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000561','00000555','APGCTXP','打印','FormQGDBILL','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000562','00000555','APGCTXP','单据设置','FormQGDBILL','ToolButtonSETCOL','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000566','00000566','APGCTXP','调平金额明细表','FrmMain','N166','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000567','00000567','APGCTXP','钢材产品定价','FrmMain','N172','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000568','00000567','APGCTXP','逐个修改','FormGoodsPrice','ButtonEdit','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000569','00000567','APGCTXP','批量设置','FormGoodsPrice','Button1','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000570','00000567','APGCTXP','导出数据','FormGoodsPrice','ToolButton3','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000572','00000567','APGCTXP','打印格式','FormGoodsPrice','ToolButton2','C')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000573','00000567','APGCTXP','打印','FormGoodsPrice','ToolButton8','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000579','00000579','APGCTXP','A型切割单','FrmMain','A1','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000580','00000579','APGCTXP','新增单据','FormQGADBILL','ToolButtonNEW','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000581','00000579','APGCTXP','编辑单据','FormQGADBILL','ToolButtonEDIT','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000582','00000579','APGCTXP','删除单据','FormQGADBILL','ToolButtonDELETE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000583','00000579','APGCTXP','单据记帐','FormQGADBILL','ToolButton1','J')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000584','00000579','APGCTXP','取消记帐','FormQGADBILL','ToolButton2','C')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000585','00000579','APGCTXP','打印','FormQGADBILL','ToolButtonPRINT','P')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000586','00000579','APGCTXP','单据设置','FormQGADBILL','ToolButtonSETCOL','X')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000589','00000589','APGCTXP','账务初始数据','FrmMain','N174','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000590','00000590','APGCTXP','启用财务帐套','FrmMain','N206','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000591','00000591','APGCTXP','反启用财务帐套','FrmMain','N208','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000592','00000599','APGCTXP','凭证录入','FrmMain','N175','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000593','00000599','APGCTXP','凭证查找','FrmMain','N176','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000594','00000599','APGCTXP','凭证审核','FrmMain','N177','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000595','00000599','APGCTXP','凭证登帐','FrmMain','N178','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000596','00000599','APGCTXP','结转损益','FrmMain','N181','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000597','00000599','APGCTXP','期末结账','FrmMain','N182','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000598','00000279','APGCTXP','导出数据','FormVENDORGJRKHZB','ToolButton3','D')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000599','00000599','APGCTXP','【财 务 管 理】','FrmMain','N112','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000600','00000599','APGCTXP','日记账','FrmMain','N184','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000601','00000599','APGCTXP','明细分类账','FrmMain','N185','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000602','00000599','APGCTXP','多栏账','FrmMain','N186','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000603','00000599','APGCTXP','总分类账','FrmMain','N187','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000604','00000599','APGCTXP','科目汇总表','FrmMain','N188','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000605','00000599','APGCTXP','科目余额汇总表','FrmMain','N190','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000606','00000599','APGCTXP','试算平衡表','FrmMain','N191','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000607','00000599','APGCTXP','利润表模版','FrmMain','N193','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000608','00000599','APGCTXP','利润表','FrmMain','N194','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000609','00000599','APGCTXP','资产负债表模版','FrmMain','N196','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000610','00000599','APGCTXP','资产负债表','FrmMain','N197','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000611','00000599','APGCTXP','现金流量代码设置','FrmMain','N200','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000612','00000599','APGCTXP','现金流量初始数据','FrmMain','N201','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000613','00000599','APGCTXP','现金流量金额分配','FrmMain','N202','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000614','00000599','APGCTXP','现金流量表模版','FrmMain','N204','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000615','00000599','APGCTXP','现金流量表','FrmMain','N205','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000616','00000599','APGCTXP','反审核','FrmMain','N212','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000617','00000599','APGCTXP','反登帐','FrmMain','N213','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000618','00000599','APGCTXP','反结账','FrmMain','N214','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000619','00000001','APGCTXP','库存价格','FormStoreDouble','ButtonPRICE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000620','00000620','APGCTXP','销售明细表','FrmMain','N215','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000621','00000621','APGCTXP','采购明细表','FrmMain','N217','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000622','00000009','APGCTXP','库存价格','FormCGTHBILL','ButtonPRICE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000623','00000017','APGCTXP','库存价格','FormXSTHBILL','ButtonPRICE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000624','00000025','APGCTXP','库存价格','FormQTRKBILL','ButtonPRICE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000625','00000041','APGCTXP','库存价格','FormQTCKBILL','ButtonPRICE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000626','00000065','APGCTXP','库存价格','FormXSCKBILL','ButtonPRICE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000627','00000073','APGCTXP','库存价格','FormCKDBBILL','ButtonPRICE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000628','00000528','APGCTXP','库存价格','FormXSDDBILL','ButtonPRICE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000629','00000537','APGCTXP','库存价格','FormCGDDBILL','ButtonPRICE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000630','00000630','APGCTXP','库存价格','DLGFormGOODSPRICE','DLGFormGOODSPRICE','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000631','00000630','APGCTXP','采购价格','DLGFormGOODSPRICE','TabSheet1','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000632','00000630','APGCTXP','销售价格','DLGFormGOODSPRICE','TabSheet2','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000633','00000630','APGCTXP','最近十次采购入库价格','DLGFormGOODSPRICE','Button1','E')
----------ENDFLAG
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000634','00000630','APGCTXP','最近十次销售出库价格','DLGFormGOODSPRICE','Button4','E')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000636','00000636','APGCTXP','入库类别','FrmMain','N220','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000637','00000637','APGCTXP','出库类别','FrmMain','N221','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000638','00000638','APGCTXP','供应商采购订单明细表','FrmMain','N224','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000639','00000639','APGCTXP','商品采购订单明细表','FrmMain','N228','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000640','00000640','APGCTXP','客户销售订单明细表','FrmMain','N227','H')
  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type)    Values  ( '00000641','00000641','APGCTXP','商品销售订单明细表','FrmMain','N229','H')



----------ENDFLAG


IF (SELECT VERSION FROM  ACCINFO  WHERE GUID='0001' ) < '7.3'  
BEGIN

CREATE TABLE [dbo].[CGRKGoodsPrice] (
	[ID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[BILLID] [varchar] (30) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[ITEMNO] [varchar] (30) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[VENDORID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
	[EMPID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
	[BILLDATE] [datetime] NULL ,
	[CODE] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
	[STOREID] [varchar] (8) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[GOODSID] [varchar] (25) COLLATE Chinese_PRC_CI_AS NULL ,
	[PRICE] [numeric](20, 10) NULL ,
	[QUANTITY] [numeric](20, 6) NULL ,
	[MEMO] [varchar] (48) COLLATE Chinese_PRC_CI_AS NULL ,
	[TAXRATE] [numeric](20, 10) NULL ,
	[DISC] [numeric](20, 10) NULL ,
	[UNITPRICE] [T_PRICE] NULL ,
	[UNITQTY] [numeric](20, 6) NULL ,
	[PRICETYPE] [smallint] NULL ,
	[AMT] [T_PRICE] NULL ,
	[TAXAMT] [T_PRICE] NULL ,
	[YunFeiFT] [numeric](18, 2) NULL ,
	[CaiZhi] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
	[ChanDi] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
	[AMOUNT] [T_PRICE] NULL ,
	[invoiceqty] [T_QUANTITY] NULL ,
	[invoiceamt] [T_PRICE] NULL ,
	[InvoiceNow] [T_PRICE] NULL ,
	[SPECNameD] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
	[JianShu] [int] NULL ,
	[MeiJianQty] [T_QUANTITY] NULL ,
	[LingTou] [T_QUANTITY] NULL ,
	[FuZhuQTY] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
	[ZongLen] [decimal](18, 4) NULL ,
	[DSPRICE] [numeric](18, 4) NULL ,
	[DSPRICETax] [numeric](18, 4) NULL ,
	[MSPRICE] [numeric](18, 4) NULL ,
	[MSPRICETax] [numeric](18, 4) NULL ,
	[CGDSPRICE] [numeric](18, 4) NULL ,
	[CGMSPRICE] [numeric](18, 4) NULL ,
	[LSRate] [numeric](18, 8) NULL ,
	[DEQTY] [numeric](18, 4) NULL ,
	[MEQTY] [numeric](18, 4) NULL 
) ON [PRIMARY]

END
----------ENDFLAG

SET ANSI_PADDING OFF
----------ENDFLAG
IF (SELECT VERSION FROM  ACCINFO  WHERE GUID='0001' ) < '7.3'  
BEGIN

ALTER TABLE [dbo].[CGRKGoodsPrice] WITH NOCHECK ADD 
	CONSTRAINT [PK_CGRKGoodsPrice] PRIMARY KEY  CLUSTERED 
	(
		[ID]
	)  ON [PRIMARY] 
END
----------ENDFLAG
IF (SELECT VERSION FROM  ACCINFO  WHERE GUID='0001' ) < '7.3'  
BEGIN

ALTER TABLE [dbo].[CGRKGoodsPrice] ADD 
	CONSTRAINT [DF_CGRKGoodsPrice_PRICE] DEFAULT (0) FOR [PRICE],
	CONSTRAINT [DF_CGRKGoodsPrice_QUANTITY] DEFAULT (0) FOR [QUANTITY],
	CONSTRAINT [DF_CGRKGoodsPrice_TAXRATE] DEFAULT (0) FOR [TAXRATE],
	CONSTRAINT [DF_CGRKGoodsPrice_DISC] DEFAULT (100) FOR [DISC],
	CONSTRAINT [DF_CGRKGoodsPrice_UNITPRICE] DEFAULT (0) FOR [UNITPRICE],
	CONSTRAINT [DF_CGRKGoodsPrice_UNITQTY] DEFAULT (0) FOR [UNITQTY],
	CONSTRAINT [DF_CGRKGoodsPrice_PRICETYPE] DEFAULT (1) FOR [PRICETYPE]
END
----------ENDFLAG


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CLIENTXSDDMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CLIENTXSDDMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODSCGDDMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GOODSCGDDMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODSXSDDMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GOODSXSDDMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VENDORCGDDMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[VENDORCGDDMXB]
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG





--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE [dbo].[CLIENTXSDDMXB]( @WHERESTING   varchar(1800)
                       
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8)

declare @GOODSNAME  varchar(50)
declare @CLIENTNAME  varchar(50)

declare @ID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @CLIENTID  nvarchar(50)
declare @GOODSCODE  nvarchar(50)
declare @SpecName  nvarchar(50)
declare @ModelName  nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLCODE  nvarchar(50)
declare @BILLTYPE INT
declare @BILLDATE  datetime
declare @CLIENTID00  nvarchar(50)
declare @PRICE NUMERIC(20, 6)
declare @TAXAMT NUMERIC(20, 2)
declare @WCunitQTY NUMERIC(20, 6)
declare @WCquantity NUMERIC(20, 6)
declare @zzunitQTY NUMERIC(20, 6)
declare @zzquantity NUMERIC(20, 6)
declare @WCTAXAMT NUMERIC(20, 6)
declare @TAXRATE  NUMERIC(20, 6)
declare @RATE  NUMERIC(20, 6)
declare @WEITAXAMT NUMERIC(20, 6)
declare @SUMWCTAXAMT NUMERIC(20, 6)
declare @SUMWEITAXAMT NUMERIC(20, 6)
declare @SUMTAXAMT NUMERIC(20, 6)
declare @UNITQTY NUMERIC(20, 6)
declare @quantity NUMERIC(20, 6)
declare @UNITPRICE NUMERIC(20, 6)
declare @DISC NUMERIC(20, 6)
declare    @PRICETYPE int

Create Table #temptable1
      (   CLIENTID varchar(50)  NULL,
       GOODSID  varchar(10) ,
       GOODSCODE  varchar(30) ,
      BILLID  nvarchar(50)  NULL,
      BILLTYPE  INT ,
	[PRICE] NUMERIC(20, 6)  NULL ,
	[UNITQTY] NUMERIC(20, 6)  NULL ,
	[quantity] NUMERIC(20, 6)  NULL ,
	[DISC] NUMERIC(20, 6)  NULL ,
	[TAXRATE]NUMERIC(20, 6)  NULL ,
	   BILLDATE  datetime  NULL,
	[UNITPRICE] NUMERIC(20, 6)  NULL ,
	[WCunitQTY]NUMERIC(20, 6)  NULL ,
	[WCquantity]NUMERIC(20, 6)  NULL ,
	[zzunitQTY]NUMERIC(20, 6)  NULL ,
	[zzquantity]NUMERIC(20, 6)  NULL ,
	[TAXAMT]NUMERIC(20, 2)  NULL, 
	[PRICETYPE]    int  NULL, 
	       DETAILBILLFLOWID  varchar(10) 
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   VIEWXSDD.CLIENTID,VIEWXSDD.GOODSID,GOODS.CODE AS GOODSCODE, BILLID,BILLTYPE,PRICE,UNITQTY,quantity,DISC,TAXRATE,BILLDATE '
           SELECT  @SQLSTR = @SQLSTR+' ,UNITPRICE,WCunitQTY,WCquantity,zzunitQTY,zzquantity,TAXAMT,PRICETYPE,DETAILBILLFLOWID  from VIEWXSDD   ,GOODS  '  + @WHERESTING +'  AND  VIEWXSDD.GOODSID = GOODS.GOODSID'
           SELECT  @SQLSTR = @SQLSTR+'  order by VIEWXSDD.CLIENTID,VIEWXSDD.GOODSID,BILLDATE,DETAILBILLFLOWID '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
	   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   GOODSNAME  nvarchar(50)  NULL,
   GOODSCODE  nvarchar(50)  NULL,
      SpecName  nvarchar(50)  NULL,
   ModelName  nvarchar(50)  NULL,
UNIT  nvarchar(10)  NULL,
	[UNITQTY] NUMERIC(20, 6)  NULL ,
	[quantity] NUMERIC(20, 6)  NULL ,
	[TAXAMT]NUMERIC(20, 2)  NULL, 
	[WCunitQTY] NUMERIC(20, 6)  NULL ,
	[WCquantity] NUMERIC(20, 6)  NULL ,
	[zzunitQTY] NUMERIC(20, 6)  NULL ,
	[zzquantity] NUMERIC(20, 6)  NULL ,
	[WCTAXAMT]NUMERIC(20, 6)  NULL ,
	[WEIunitQTY] NUMERIC(20, 6)  NULL ,
	[WEIquantity] NUMERIC(20, 6)  NULL ,
	[WEITAXAMT]NUMERIC(20, 6)  NULL 
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (select  CLIENTID, GOODSID, BILLID,PRICE,UNITQTY,TAXRATE,BILLTYPE   from  #temptable1        )
                 begin
	    declare XSDDMXB_CLIENT Cursor for select  CLIENTID, GOODSID, BILLID,PRICE,UNITQTY,quantity,TAXRATE,BILLTYPE ,DISC,UNITPRICE,WCunitQTY,WCquantity, zzunitQTY,zzquantity,TAXAMT,PRICETYPE  from  #temptable1  
---                                                            ORDER BY  CLIENTID,  BILLDATE,DETAILBILLFLOWID,GOODSCODE
                                                            ORDER BY  CLIENTID,  BILLDATE,BILLID,GOODSCODE
	    Open XSDDMXB_CLIENT

	    fetch XSDDMXB_CLIENT into   @CLIENTID,@GOODSID,@BILLID,@PRICE,@UNITQTY,@quantity,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@WCunitQTY,@WCquantity,@zzunitQTY,@zzquantity,@TAXAMT,@PRICETYPE

                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @CLIENTNAME =(SELECT NAME   FROM CLIENT  WHERE CLIENTID=@CLIENTID)
                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)

                 SELECT  @CLIENTID00=@CLIENTID

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                                           VALUES  (@COUNTID,@CLIENTNAME)
		SELECT @SUMWCTAXAMT=0
		SELECT @SUMTAXAMT=0
		SELECT @SUMWEITAXAMT=0
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF  not( @CLIENTID00 = @CLIENTID)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,WCTAXAMT,TAXAMT,WEITAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMWCTAXAMT,@SUMTAXAMT,@SUMWEITAXAMT)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @CLIENTNAME =(SELECT NAME   FROM CLIENT  WHERE CLIENTID=@CLIENTID)
		                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @CLIENTID00=@CLIENTID


			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                           	                VALUES  (@COUNTID,@CLIENTNAME)
				SELECT @SUMWCTAXAMT=0
				SELECT @SUMTAXAMT=0
				SELECT @SUMWEITAXAMT=0
		END	
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

				--SELECT @RATE =RATE  FROM GOODSUNIT  WHERE GOODSID=@GOODSID AND UNITID=@UNITID

	  			SELECT @UNIT = (SELECT UNIT   FROM GOODS  WHERE GOODSID=@GOODSID)
				
			   SELECT @BILLCODE=(SELECT CODE   FROM STOREXSDDM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STOREXSDDM  WHERE BILLID=@BILLID)
               SELECT  @GOODSCODE=CODE,@GOODSNAME=Name,@SpecName=SpecName,@ModelName=ModelName     FROM GOODS  WHERE GOODSID=@GOODSID
		               if @PRICETYPE=1
		               begin  
		                 SET @WEITAXAMT=Round(ISNULL(@DISC,100)*0.01*(ISNULL(@quantity,0)-ISNULL(@WCquantity,0)-ISNULL(@zzquantity,0))*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
		                 SET @WCTAXAMT=Round(ISNULL(@DISC,100)*0.01*ISNULL(@WCquantity,0)*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
					   end
					   else
					   begin
		                 SET @WEITAXAMT=Round(ISNULL(@DISC,100)*0.01*(ISNULL(@unitqty,0)-ISNULL(@WCunitqty,0)-ISNULL(@zzunitqty,0))*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
		                 SET @WCTAXAMT=Round(ISNULL(@DISC,100)*0.01*ISNULL(@WCunitqty,0)*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
					   end
		                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,GOODSNAME,GOODSCODE,SpecName,ModelName,UNIT, UNITQTY,quantity,TAXAMT,WCunitQTY,WCquantity,zzunitQTY,zzquantity,WCTAXAMT,WEIunitQTY,WEIquantity,WEITAXAMT)
             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@GOODSNAME,@GOODSCODE,@SpecName,@ModelName,@UNIT,@UNITQTY,@quantity,
					                     @TAXAMT,
					                     ISNULL(@WCunitQTY,0) ,
					                     ISNULL(@WCquantity,0) ,
					                     ISNULL(@zzunitQTY,0) ,
					                     ISNULL(@zzquantity,0) ,					@WCTAXAMT,
					                      @UNITQTY-ISNULL(@WCunitQTY,0) -ISNULL(@zzunitQTY,0),
					                      @quantity-ISNULL(@WCquantity,0) -ISNULL(@zzquantity,0),@WEITAXAMT	)

				SELECT @SUMTAXAMT=@SUMTAXAMT+@TAXAMT
				SELECT @SUMWCTAXAMT=@SUMWCTAXAMT+@WCTAXAMT
				SELECT @SUMWEITAXAMT=@SUMWEITAXAMT+@WEITAXAMT
		
	    fetch XSDDMXB_CLIENT into   @CLIENTID,@GOODSID,@BILLID,@PRICE,@UNITQTY,@quantity,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@WCunitQTY,@WCquantity,@zzunitQTY,@zzquantity,@TAXAMT,@PRICETYPE
 
	    END           ------- XSDDMXB_CLIENT  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,WCTAXAMT,TAXAMT,WEITAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMWCTAXAMT,@SUMTAXAMT,@SUMWEITAXAMT)

	    close XSDDMXB_CLIENT
	    deallocate XSDDMXB_CLIENT
        end     ------------  if exists

 SELECT *  FROM #temptable2         ORDER BY ID










----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG





--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE [dbo].[GOODSCGDDMXB]( @WHERESTING   varchar(1800)
                       
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8)

declare @VENDORNAME  varchar(50)
declare @GOODSNAME  varchar(50)

declare @ID  nvarchar(50)
declare @VENDORID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @VENDORCODE  nvarchar(50)
declare @GOODSCODE  nvarchar(50)
declare @SPECNAME nvarchar(50)
declare @MODELNAME nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLCODE  nvarchar(50)
declare @BILLTYPE INT
declare @BILLDATE  datetime
declare @GOODSID00  nvarchar(50)
declare @PRICE NUMERIC(20, 6)
declare @TAXAMT NUMERIC(20, 2)
declare @WCunitQTY NUMERIC(20, 6)
declare @WCquantity NUMERIC(20, 6)
declare @zzunitQTY NUMERIC(20, 6)
declare @zzquantity NUMERIC(20, 6)
declare @WCTAXAMT NUMERIC(20, 6)
declare @TAXRATE  NUMERIC(20, 6)
declare @RATE  NUMERIC(20, 6)
declare @WEITAXAMT NUMERIC(20, 6)
declare @SUMWCTAXAMT NUMERIC(20, 6)
declare @SUMWEITAXAMT NUMERIC(20, 6)
declare @SUMTAXAMT NUMERIC(20, 6)
declare @UNITQTY NUMERIC(20, 6)
declare @quantity NUMERIC(20, 6)
declare @UNITPRICE NUMERIC(20, 6)
declare @DISC NUMERIC(20, 6)
declare    @PRICETYPE int

Create Table #temptable1
      (   GOODSID varchar(50)  NULL,
       VENDORID  varchar(10) ,
       VENDORCODE  varchar(30) ,
      BILLID  nvarchar(50)  NULL,
      BILLTYPE  INT ,
	[PRICE] NUMERIC(20, 6)  NULL ,
	[UNITQTY] NUMERIC(20, 6)  NULL ,
	[quantity] NUMERIC(20, 6)  NULL ,
	[DISC] NUMERIC(20, 6)  NULL ,
	[TAXRATE]NUMERIC(20, 6)  NULL ,
	   BILLDATE  datetime  NULL,
	[UNITPRICE] NUMERIC(20, 6)  NULL ,
	[WCunitQTY]NUMERIC(20, 6)  NULL ,
	[WCquantity]NUMERIC(20, 6)  NULL ,
	[zzunitQTY]NUMERIC(20, 6)  NULL ,
	[zzquantity]NUMERIC(20, 6)  NULL ,
	[TAXAMT]NUMERIC(20, 2)  NULL, 
	[PRICETYPE]    int  NULL, 
	       DETAILBILLFLOWID  varchar(10) 
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   VIEWCGDD.GOODSID,VIEWCGDD.VENDORID,VENDOR.CODE AS VENDORCODE, BILLID,BILLTYPE,PRICE,UNITQTY,quantity,DISC,TAXRATE,BILLDATE '
           SELECT  @SQLSTR = @SQLSTR+' ,UNITPRICE,WCunitQTY,WCquantity,zzunitQTY,zzquantity,TAXAMT,PRICETYPE,DETAILBILLFLOWID  from VIEWCGDD   ,VENDOR  '  + @WHERESTING +'  AND  VIEWCGDD.VENDORID = VENDOR.VENDORID'
           SELECT  @SQLSTR = @SQLSTR+'  order by VIEWCGDD.GOODSID,VIEWCGDD.VENDORID,BILLDATE,DETAILBILLFLOWID '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
	   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   VENDORNAME  nvarchar(50)  NULL,
   VENDORCODE  nvarchar(50)  NULL,
   UNIT  nvarchar(10)  NULL,
	[UNITQTY] NUMERIC(20, 6)  NULL ,
	[quantity] NUMERIC(20, 6)  NULL ,
	[TAXAMT]NUMERIC(20, 2)  NULL, 
	[WCunitQTY] NUMERIC(20, 6)  NULL ,
	[WCquantity] NUMERIC(20, 6)  NULL ,
	[zzunitQTY] NUMERIC(20, 6)  NULL ,
	[zzquantity] NUMERIC(20, 6)  NULL ,
	[WCTAXAMT]NUMERIC(20, 6)  NULL ,
	[WEIunitQTY] NUMERIC(20, 6)  NULL ,
	[WEIquantity] NUMERIC(20, 6)  NULL ,
	[WEITAXAMT]NUMERIC(20, 6)  NULL 
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (select  GOODSID, VENDORID, BILLID,PRICE,UNITQTY,TAXRATE,BILLTYPE   from  #temptable1        )
                 begin
	    declare CGDDMXB_GOODS Cursor for select  GOODSID, VENDORID, BILLID,PRICE,UNITQTY,quantity,TAXRATE,BILLTYPE ,DISC,UNITPRICE,WCunitQTY,WCquantity, zzunitQTY,zzquantity,TAXAMT,PRICETYPE  from  #temptable1  
---                                                            ORDER BY  GOODSID,  BILLDATE,DETAILBILLFLOWID,VENDORCODE
                                                            ORDER BY  GOODSID,  BILLDATE,BILLID,VENDORCODE
	    Open CGDDMXB_GOODS

	    fetch CGDDMXB_GOODS into   @GOODSID,@VENDORID,@BILLID,@PRICE,@UNITQTY,@quantity,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@WCunitQTY,@WCquantity,@zzunitQTY,@zzquantity,@TAXAMT,@PRICETYPE

                 SELECT  @VENDORNAME =(SELECT NAME   FROM VENDOR  WHERE VENDORID=@VENDORID)
                 SELECT  @VENDORCODE =(SELECT CODE  FROM VENDOR  WHERE VENDORID=@VENDORID)
                 SELECT  @GOODSCODE=CODE,@GOODSNAME=Name,@SpecName=SpecName,@ModelName=ModelName     FROM GOODS  WHERE GOODSID=@GOODSID
                 SELECT  @GOODSNAME =@GOODSNAME+' '+ISNULL(@SpecName,'')+' '+ISNULL(@ModelName,'')
                 SELECT  @GOODSCODE='钢材编码：'+@GOODSCODE

                 SELECT  @GOODSID00=@GOODSID

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,VENDORNAME         )
                                           VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
		SELECT @SUMWCTAXAMT=0
		SELECT @SUMTAXAMT=0
		SELECT @SUMWEITAXAMT=0
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF  not( @GOODSID00 = @GOODSID)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,WCTAXAMT,TAXAMT,WEITAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMWCTAXAMT,@SUMTAXAMT,@SUMWEITAXAMT)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

		                 SELECT  @VENDORNAME =(SELECT NAME   FROM VENDOR  WHERE VENDORID=@VENDORID)
		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @VENDORCODE =(SELECT CODE  FROM VENDOR  WHERE VENDORID=@VENDORID)
                 SELECT  @GOODSCODE=CODE,@GOODSNAME=Name,@SpecName=SpecName,@ModelName=ModelName     FROM GOODS  WHERE GOODSID=@GOODSID
                 SELECT  @GOODSNAME =@GOODSNAME+' '+ISNULL(@SpecName,'')+' '+ISNULL(@ModelName,'')
                 SELECT  @GOODSCODE='钢材编码：'+@GOODSCODE
		                 
		                 SELECT  @GOODSID00=@GOODSID


			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,VENDORNAME         )
                                           VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
				SELECT @SUMWCTAXAMT=0
				SELECT @SUMTAXAMT=0
				SELECT @SUMWEITAXAMT=0
		END	
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

				--SELECT @RATE =RATE  FROM VENDORUNIT  WHERE VENDORID=@VENDORID AND UNITID=@UNITID

			SELECT @UNIT = UNIT   FROM GOODS  WHERE GOODSID=@GOODSID
				
			   SELECT @BILLCODE=(SELECT CODE   FROM STORECGDDM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STORECGDDM  WHERE BILLID=@BILLID)
		                 SELECT  @VENDORNAME=(SELECT NAME   FROM VENDOR  WHERE VENDORID=@VENDORID)
		                 SELECT  @VENDORCODE=(SELECT CODE   FROM VENDOR  WHERE VENDORID=@VENDORID)
		               if @PRICETYPE=1
		               begin  
		                 SET @WEITAXAMT=Round(ISNULL(@DISC,100)*0.01*(ISNULL(@quantity,0)-ISNULL(@WCquantity,0)-ISNULL(@zzquantity,0))*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
		                 SET @WCTAXAMT=Round(ISNULL(@DISC,100)*0.01*ISNULL(@WCquantity,0)*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
					   end
					   else
					   begin
		                 SET @WEITAXAMT=Round(ISNULL(@DISC,100)*0.01*(ISNULL(@unitqty,0)-ISNULL(@WCunitqty,0)-ISNULL(@zzunitqty,0))*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
		                 SET @WCTAXAMT=Round(ISNULL(@DISC,100)*0.01*ISNULL(@WCunitqty,0)*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
					   end
		                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,VENDORNAME,VENDORCODE,UNIT, UNITQTY,quantity,TAXAMT,WCunitQTY,WCquantity,zzunitQTY,zzquantity,WCTAXAMT,WEIunitQTY,WEIquantity,WEITAXAMT)
             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@VENDORNAME,@VENDORCODE,@UNIT,@UNITQTY,@quantity,
					                     @TAXAMT,
					                     ISNULL(@WCunitQTY,0) ,
					                     ISNULL(@WCquantity,0) ,
					                     ISNULL(@zzunitQTY,0) ,
					                     ISNULL(@zzquantity,0) ,					@WCTAXAMT,
					                      @UNITQTY-ISNULL(@WCunitQTY,0) -ISNULL(@zzunitQTY,0),
					                      @quantity-ISNULL(@WCquantity,0) -ISNULL(@zzquantity,0),@WEITAXAMT	)

				SELECT @SUMTAXAMT=@SUMTAXAMT+@TAXAMT
				SELECT @SUMWCTAXAMT=@SUMWCTAXAMT+@WCTAXAMT
				SELECT @SUMWEITAXAMT=@SUMWEITAXAMT+@WEITAXAMT
		
	    fetch CGDDMXB_GOODS into   @GOODSID,@VENDORID,@BILLID,@PRICE,@UNITQTY,@quantity,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@WCunitQTY,@WCquantity,@zzunitQTY,@zzquantity,@TAXAMT,@PRICETYPE
 
	    END           ------- CGDDMXB_GOODS  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,WCTAXAMT,TAXAMT,WEITAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMWCTAXAMT,@SUMTAXAMT,@SUMWEITAXAMT)

	    close CGDDMXB_GOODS
	    deallocate CGDDMXB_GOODS
        end     ------------  if exists

 SELECT *  FROM #temptable2         ORDER BY ID










----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG






--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE [dbo].[GOODSXSDDMXB]( @WHERESTING   varchar(1800)
                       
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8)

declare @CLIENTNAME  varchar(50)
declare @GOODSNAME  varchar(50)

declare @ID  nvarchar(50)
declare @CLIENTID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @CLIENTCODE  nvarchar(50)
declare @GOODSCODE  nvarchar(50)
declare @SPECNAME nvarchar(50)
declare @MODELNAME nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLCODE  nvarchar(50)
declare @BILLTYPE INT
declare @BILLDATE  datetime
declare @GOODSID00  nvarchar(50)
declare @PRICE NUMERIC(20, 6)
declare @TAXAMT NUMERIC(20, 2)
declare @WCunitQTY NUMERIC(20, 6)
declare @WCquantity NUMERIC(20, 6)
declare @zzunitQTY NUMERIC(20, 6)
declare @zzquantity NUMERIC(20, 6)
declare @WCTAXAMT NUMERIC(20, 6)
declare @TAXRATE  NUMERIC(20, 6)
declare @RATE  NUMERIC(20, 6)
declare @WEITAXAMT NUMERIC(20, 6)
declare @SUMWCTAXAMT NUMERIC(20, 6)
declare @SUMWEITAXAMT NUMERIC(20, 6)
declare @SUMTAXAMT NUMERIC(20, 6)
declare @UNITQTY NUMERIC(20, 6)
declare @quantity NUMERIC(20, 6)
declare @UNITPRICE NUMERIC(20, 6)
declare @DISC NUMERIC(20, 6)
declare    @PRICETYPE int

Create Table #temptable1
      (   GOODSID varchar(50)  NULL,
       CLIENTID  varchar(10) ,
       CLIENTCODE  varchar(30) ,
      BILLID  nvarchar(50)  NULL,
      BILLTYPE  INT ,
	[PRICE] NUMERIC(20, 6)  NULL ,
	[UNITQTY] NUMERIC(20, 6)  NULL ,
	[quantity] NUMERIC(20, 6)  NULL ,
	[DISC] NUMERIC(20, 6)  NULL ,
	[TAXRATE]NUMERIC(20, 6)  NULL ,
	   BILLDATE  datetime  NULL,
	[UNITPRICE] NUMERIC(20, 6)  NULL ,
	[WCunitQTY]NUMERIC(20, 6)  NULL ,
	[WCquantity]NUMERIC(20, 6)  NULL ,
	[zzunitQTY]NUMERIC(20, 6)  NULL ,
	[zzquantity]NUMERIC(20, 6)  NULL ,
	[TAXAMT]NUMERIC(20, 2)  NULL, 
	[PRICETYPE]    int  NULL, 
	       DETAILBILLFLOWID  varchar(10) 
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   VIEWXSDD.GOODSID,VIEWXSDD.CLIENTID,CLIENT.CODE AS CLIENTCODE, BILLID,BILLTYPE,PRICE,UNITQTY,quantity,DISC,TAXRATE,BILLDATE '
           SELECT  @SQLSTR = @SQLSTR+' ,UNITPRICE,WCunitQTY,WCquantity,zzunitQTY,zzquantity,TAXAMT,PRICETYPE,DETAILBILLFLOWID  from VIEWXSDD   ,CLIENT  '  + @WHERESTING +'  AND  VIEWXSDD.CLIENTID = CLIENT.CLIENTID'
           SELECT  @SQLSTR = @SQLSTR+'  order by VIEWXSDD.GOODSID,VIEWXSDD.CLIENTID,BILLDATE,DETAILBILLFLOWID '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
	   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   CLIENTNAME  nvarchar(50)  NULL,
   CLIENTCODE  nvarchar(50)  NULL,
   UNIT  nvarchar(10)  NULL,
	[UNITQTY] NUMERIC(20, 6)  NULL ,
	[quantity] NUMERIC(20, 6)  NULL ,
	[TAXAMT]NUMERIC(20, 2)  NULL, 
	[WCunitQTY] NUMERIC(20, 6)  NULL ,
	[WCquantity] NUMERIC(20, 6)  NULL ,
	[zzunitQTY] NUMERIC(20, 6)  NULL ,
	[zzquantity] NUMERIC(20, 6)  NULL ,
	[WCTAXAMT]NUMERIC(20, 6)  NULL ,
	[WEIunitQTY] NUMERIC(20, 6)  NULL ,
	[WEIquantity] NUMERIC(20, 6)  NULL ,
	[WEITAXAMT]NUMERIC(20, 6)  NULL 
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (select  GOODSID, CLIENTID, BILLID,PRICE,UNITQTY,TAXRATE,BILLTYPE   from  #temptable1        )
                 begin
	    declare XSDDMXB_GOODS Cursor for select  GOODSID, CLIENTID, BILLID,PRICE,UNITQTY,quantity,TAXRATE,BILLTYPE ,DISC,UNITPRICE,WCunitQTY,WCquantity, zzunitQTY,zzquantity,TAXAMT,PRICETYPE  from  #temptable1  
---                                                            ORDER BY  GOODSID,  BILLDATE,DETAILBILLFLOWID,CLIENTCODE
                                                            ORDER BY  GOODSID,  BILLDATE,BILLID,CLIENTCODE
	    Open XSDDMXB_GOODS

	    fetch XSDDMXB_GOODS into   @GOODSID,@CLIENTID,@BILLID,@PRICE,@UNITQTY,@quantity,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@WCunitQTY,@WCquantity,@zzunitQTY,@zzquantity,@TAXAMT,@PRICETYPE

                 SELECT  @CLIENTNAME =(SELECT NAME   FROM CLIENT  WHERE CLIENTID=@CLIENTID)
                 SELECT  @CLIENTCODE =(SELECT CODE  FROM CLIENT  WHERE CLIENTID=@CLIENTID)
                 SELECT  @GOODSCODE=CODE,@GOODSNAME=Name,@SpecName=SpecName,@ModelName=ModelName     FROM GOODS  WHERE GOODSID=@GOODSID
                 SELECT  @GOODSNAME =@GOODSNAME+' '+ISNULL(@SpecName,'')+' '+ISNULL(@ModelName,'')
                 SELECT  @GOODSCODE='钢材编码：'+@GOODSCODE

                 SELECT  @GOODSID00=@GOODSID

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,CLIENTNAME         )
                                           VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
		SELECT @SUMWCTAXAMT=0
		SELECT @SUMTAXAMT=0
		SELECT @SUMWEITAXAMT=0
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF  not( @GOODSID00 = @GOODSID)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,WCTAXAMT,TAXAMT,WEITAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMWCTAXAMT,@SUMTAXAMT,@SUMWEITAXAMT)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

		                 SELECT  @CLIENTNAME =(SELECT NAME   FROM CLIENT  WHERE CLIENTID=@CLIENTID)
		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @CLIENTCODE =(SELECT CODE  FROM CLIENT  WHERE CLIENTID=@CLIENTID)
                 SELECT  @GOODSCODE=CODE,@GOODSNAME=Name,@SpecName=SpecName,@ModelName=ModelName     FROM GOODS  WHERE GOODSID=@GOODSID
                 SELECT  @GOODSNAME =@GOODSNAME+' '+ISNULL(@SpecName,'')+' '+ISNULL(@ModelName,'')
                 SELECT  @GOODSCODE='钢材编码：'+@GOODSCODE
		                 
		                 SELECT  @GOODSID00=@GOODSID


			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,CLIENTNAME         )
                                           VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
				SELECT @SUMWCTAXAMT=0
				SELECT @SUMTAXAMT=0
				SELECT @SUMWEITAXAMT=0
		END	
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

				--SELECT @RATE =RATE  FROM CLIENTUNIT  WHERE CLIENTID=@CLIENTID AND UNITID=@UNITID

			SELECT @UNIT = UNIT   FROM GOODS  WHERE GOODSID=@GOODSID
				
			   SELECT @BILLCODE=(SELECT CODE   FROM STOREXSDDM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STOREXSDDM  WHERE BILLID=@BILLID)
		                 SELECT  @CLIENTNAME=(SELECT NAME   FROM CLIENT  WHERE CLIENTID=@CLIENTID)
		                 SELECT  @CLIENTCODE=(SELECT CODE   FROM CLIENT  WHERE CLIENTID=@CLIENTID)
		               if @PRICETYPE=1
		               begin  
		                 SET @WEITAXAMT=Round(ISNULL(@DISC,100)*0.01*(ISNULL(@quantity,0)-ISNULL(@WCquantity,0)-ISNULL(@zzquantity,0))*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
		                 SET @WCTAXAMT=Round(ISNULL(@DISC,100)*0.01*ISNULL(@WCquantity,0)*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
					   end
					   else
					   begin
		                 SET @WEITAXAMT=Round(ISNULL(@DISC,100)*0.01*(ISNULL(@unitqty,0)-ISNULL(@WCunitqty,0)-ISNULL(@zzunitqty,0))*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
		                 SET @WCTAXAMT=Round(ISNULL(@DISC,100)*0.01*ISNULL(@WCunitqty,0)*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
					   end
		                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,CLIENTNAME,CLIENTCODE,UNIT, UNITQTY,quantity,TAXAMT,WCunitQTY,WCquantity,zzunitQTY,zzquantity,WCTAXAMT,WEIunitQTY,WEIquantity,WEITAXAMT)
             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@CLIENTNAME,@CLIENTCODE,@UNIT,@UNITQTY,@quantity,
					                     @TAXAMT,
					                     ISNULL(@WCunitQTY,0) ,
					                     ISNULL(@WCquantity,0) ,
					                     ISNULL(@zzunitQTY,0) ,
					                     ISNULL(@zzquantity,0) ,					@WCTAXAMT,
					                      @UNITQTY-ISNULL(@WCunitQTY,0) -ISNULL(@zzunitQTY,0),
					                      @quantity-ISNULL(@WCquantity,0) -ISNULL(@zzquantity,0),@WEITAXAMT	)

				SELECT @SUMTAXAMT=@SUMTAXAMT+@TAXAMT
				SELECT @SUMWCTAXAMT=@SUMWCTAXAMT+@WCTAXAMT
				SELECT @SUMWEITAXAMT=@SUMWEITAXAMT+@WEITAXAMT
		
	    fetch XSDDMXB_GOODS into   @GOODSID,@CLIENTID,@BILLID,@PRICE,@UNITQTY,@quantity,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@WCunitQTY,@WCquantity,@zzunitQTY,@zzquantity,@TAXAMT,@PRICETYPE
 
	    END           ------- XSDDMXB_GOODS  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,WCTAXAMT,TAXAMT,WEITAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMWCTAXAMT,@SUMTAXAMT,@SUMWEITAXAMT)

	    close XSDDMXB_GOODS
	    deallocate XSDDMXB_GOODS
        end     ------------  if exists

 SELECT *  FROM #temptable2         ORDER BY ID











----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG




--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE [dbo].[VENDORCGDDMXB]( @WHERESTING   varchar(1800)                       
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8)

declare @GOODSNAME  varchar(50)
declare @VENDORNAME  varchar(50)

declare @ID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @VENDORID  nvarchar(50)
declare @GOODSCODE  nvarchar(50)
declare @SpecName  nvarchar(50)
declare @ModelName  nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLCODE  nvarchar(50)
declare @BILLTYPE INT
declare @BILLDATE  datetime
declare @VENDORID00  nvarchar(50)
declare @PRICE NUMERIC(20, 6)
declare @TAXAMT NUMERIC(20, 2)
declare @WCunitQTY NUMERIC(20, 6)
declare @WCquantity NUMERIC(20, 6)
declare @zzunitQTY NUMERIC(20, 6)
declare @zzquantity NUMERIC(20, 6)
declare @WCTAXAMT NUMERIC(20, 6)
declare @TAXRATE  NUMERIC(20, 6)
declare @RATE  NUMERIC(20, 6)
declare @WEITAXAMT NUMERIC(20, 6)
declare @SUMWCTAXAMT NUMERIC(20, 6)
declare @SUMWEITAXAMT NUMERIC(20, 6)
declare @SUMTAXAMT NUMERIC(20, 6)
declare @UNITQTY NUMERIC(20, 6)
declare @quantity NUMERIC(20, 6)
declare @UNITPRICE NUMERIC(20, 6)
declare @DISC NUMERIC(20, 6)
declare    @PRICETYPE int

Create Table #temptable1
      (   VENDORID varchar(50)  NULL,
       GOODSID  varchar(10) ,
       GOODSCODE  varchar(30) ,
      BILLID  nvarchar(50)  NULL,
      BILLTYPE  INT ,
	[PRICE] NUMERIC(20, 6)  NULL ,
	[UNITQTY] NUMERIC(20, 6)  NULL ,
	[quantity] NUMERIC(20, 6)  NULL ,
	[DISC] NUMERIC(20, 6)  NULL ,
	[TAXRATE]NUMERIC(20, 6)  NULL ,
	   BILLDATE  datetime  NULL,
	[UNITPRICE] NUMERIC(20, 6)  NULL ,
	[WCunitQTY]NUMERIC(20, 6)  NULL ,
	[WCquantity]NUMERIC(20, 6)  NULL ,
	[zzunitQTY]NUMERIC(20, 6)  NULL ,
	[zzquantity]NUMERIC(20, 6)  NULL ,
	[TAXAMT]NUMERIC(20, 2)  NULL, 
	[PRICETYPE]    int  NULL, 
	       DETAILBILLFLOWID  varchar(10) 
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   VIEWCGDD.VENDORID,VIEWCGDD.GOODSID,GOODS.CODE AS GOODSCODE, BILLID,BILLTYPE,PRICE,UNITQTY,quantity,DISC,TAXRATE,BILLDATE '
           SELECT  @SQLSTR = @SQLSTR+' ,UNITPRICE,WCunitQTY,WCquantity,zzunitQTY,zzquantity,TAXAMT,PRICETYPE,DETAILBILLFLOWID  from VIEWCGDD   ,GOODS  '  + @WHERESTING +'  AND  VIEWCGDD.GOODSID = GOODS.GOODSID'
           SELECT  @SQLSTR = @SQLSTR+'  order by VIEWCGDD.VENDORID,VIEWCGDD.GOODSID,BILLDATE,DETAILBILLFLOWID '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
	   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   GOODSNAME  nvarchar(50)  NULL,
   GOODSCODE  nvarchar(50)  NULL,
   SpecName  nvarchar(50)  NULL,
   ModelName  nvarchar(50)  NULL,
   UNIT  nvarchar(10)  NULL,
	[UNITQTY] NUMERIC(20, 6)  NULL ,
	[quantity] NUMERIC(20, 6)  NULL ,
	[TAXAMT]NUMERIC(20, 2)  NULL, 
	[WCunitQTY] NUMERIC(20, 6)  NULL ,
	[WCquantity] NUMERIC(20, 6)  NULL ,
	[zzunitQTY] NUMERIC(20, 6)  NULL ,
	[zzquantity] NUMERIC(20, 6)  NULL ,
	[WCTAXAMT]NUMERIC(20, 6)  NULL ,
	[WEIunitQTY] NUMERIC(20, 6)  NULL ,
	[WEIquantity] NUMERIC(20, 6)  NULL ,
	[WEITAXAMT]NUMERIC(20, 6)  NULL 
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (select  VENDORID, GOODSID, BILLID,PRICE,UNITQTY,TAXRATE,BILLTYPE   from  #temptable1        )
                 begin
	    declare CGDDMXB_VENDOR Cursor for select  VENDORID, GOODSID, BILLID,PRICE,UNITQTY,quantity,TAXRATE,BILLTYPE ,DISC,UNITPRICE,WCunitQTY,WCquantity, zzunitQTY,zzquantity,TAXAMT,PRICETYPE  from  #temptable1  
---                                                            ORDER BY  VENDORID,  BILLDATE,DETAILBILLFLOWID,GOODSCODE
                                                            ORDER BY  VENDORID,  BILLDATE,BILLID,GOODSCODE
	    Open CGDDMXB_VENDOR

	    fetch CGDDMXB_VENDOR into   @VENDORID,@GOODSID,@BILLID,@PRICE,@UNITQTY,@quantity,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@WCunitQTY,@WCquantity,@zzunitQTY,@zzquantity,@TAXAMT,@PRICETYPE

                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @VENDORNAME =(SELECT NAME   FROM VENDOR  WHERE VENDORID=@VENDORID)
                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)

                 SELECT  @VENDORID00=@VENDORID

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                                           VALUES  (@COUNTID,@VENDORNAME)
		SELECT @SUMWCTAXAMT=0
		SELECT @SUMTAXAMT=0
		SELECT @SUMWEITAXAMT=0
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF  not( @VENDORID00 = @VENDORID)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,WCTAXAMT,TAXAMT,WEITAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMWCTAXAMT,@SUMTAXAMT,@SUMWEITAXAMT)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @VENDORNAME =(SELECT NAME   FROM VENDOR  WHERE VENDORID=@VENDORID)
		                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @VENDORID00=@VENDORID


			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                           	                VALUES  (@COUNTID,@VENDORNAME)
				SELECT @SUMWCTAXAMT=0
				SELECT @SUMTAXAMT=0
				SELECT @SUMWEITAXAMT=0
		END	
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

				--SELECT @RATE =RATE  FROM GOODSUNIT  WHERE GOODSID=@GOODSID AND UNITID=@UNITID

	  			SELECT @UNIT = (SELECT UNIT   FROM GOODS  WHERE GOODSID=@GOODSID)
				
			   SELECT @BILLCODE=(SELECT CODE   FROM STORECGDDM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STORECGDDM  WHERE BILLID=@BILLID)
               SELECT  @GOODSCODE=CODE,@GOODSNAME=Name,@SpecName=SpecName,@ModelName=ModelName     FROM GOODS  WHERE GOODSID=@GOODSID
	               if @PRICETYPE=1
		               begin  
		                 SET @WEITAXAMT=Round(ISNULL(@DISC,100)*0.01*(ISNULL(@quantity,0)-ISNULL(@WCquantity,0)-ISNULL(@zzquantity,0))*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
		                 SET @WCTAXAMT=Round(ISNULL(@DISC,100)*0.01*ISNULL(@WCquantity,0)*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
					   end
					   else
					   begin
		                 SET @WEITAXAMT=Round(ISNULL(@DISC,100)*0.01*(ISNULL(@unitqty,0)-ISNULL(@WCunitqty,0)-ISNULL(@zzunitqty,0))*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
		                 SET @WCTAXAMT=Round(ISNULL(@DISC,100)*0.01*ISNULL(@WCunitqty,0)*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
					   end
		                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,GOODSNAME,GOODSCODE,SpecName,ModelName,UNIT, UNITQTY,quantity,TAXAMT,WCunitQTY,WCquantity,zzunitQTY,zzquantity,WCTAXAMT,WEIunitQTY,WEIquantity,WEITAXAMT)
             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@GOODSNAME,@GOODSCODE,@SpecName,@ModelName,@UNIT,@UNITQTY,@quantity,
					                     @TAXAMT,
					                     ISNULL(@WCunitQTY,0) ,
					                     ISNULL(@WCquantity,0) ,
					                     ISNULL(@zzunitQTY,0) ,
					                     ISNULL(@zzquantity,0) ,					@WCTAXAMT,
					                      @UNITQTY-ISNULL(@WCunitQTY,0) -ISNULL(@zzunitQTY,0),
					                      @quantity-ISNULL(@WCquantity,0) -ISNULL(@zzquantity,0),@WEITAXAMT	)

				SELECT @SUMTAXAMT=@SUMTAXAMT+@TAXAMT
				SELECT @SUMWCTAXAMT=@SUMWCTAXAMT+@WCTAXAMT
				SELECT @SUMWEITAXAMT=@SUMWEITAXAMT+@WEITAXAMT
		
	    fetch CGDDMXB_VENDOR into   @VENDORID,@GOODSID,@BILLID,@PRICE,@UNITQTY,@quantity,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@WCunitQTY,@WCquantity,@zzunitQTY,@zzquantity,@TAXAMT,@PRICETYPE
 
	    END           ------- CGDDMXB_VENDOR  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,WCTAXAMT,TAXAMT,WEITAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMWCTAXAMT,@SUMTAXAMT,@SUMWEITAXAMT)

	    close CGDDMXB_VENDOR
	    deallocate CGDDMXB_VENDOR
        end     ------------  if exists

 SELECT *  FROM #temptable2         ORDER BY ID









----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG


if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[APRICECACULATOR_STORE ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[APRICECACULATOR_STORE ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[APRICECACULATOR_STORE_XIAN ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[APRICECACULATOR_STORE_XIAN ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[APRICECACULATOR_YYYYMM ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[APRICECACULATOR_YYYYMM ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[APRICECACULATOR_YYYYMM_XIAN ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[APRICECACULATOR_YYYYMM_XIAN ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BANKINOUTMXBREP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BANKINOUTMXBREP]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BANKYYYYMMDD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BANKYYYYMMDD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BANK_CACULATOR_YYYYMM ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BANK_CACULATOR_YYYYMM ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BETWEEN_CURR_YYYYMM]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BETWEEN_CURR_YYYYMM]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Bs_Update_AREATree]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Bs_Update_AREATree]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Bs_Update_GoodsTypeTree]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Bs_Update_GoodsTypeTree]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Bs_Update_INTYPETree]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Bs_Update_INTYPETree]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Bs_Update_OUTTYPETree]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Bs_Update_OUTTYPETree]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CGRKGoodsPrice_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CGRKGoodsPrice_Update]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CLIENTINOUTMXBREP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CLIENTINOUTMXBREP]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CLIENTXSCKMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CLIENTXSCKMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CLIENTXSDDMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CLIENTXSDDMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CLIENTYYYYMMDD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CLIENTYYYYMMDD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CLIENTYYYYMMDD_BJ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CLIENTYYYYMMDD_BJ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CLIENT_CACULATOR_YYYYMM ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CLIENT_CACULATOR_YYYYMM ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CREAT_QGD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CREAT_QGD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CREAT_STRING_BILLNAME]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CREAT_STRING_BILLNAME]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CREAT_STRING_BillSeeAbout]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CREAT_STRING_BillSeeAbout]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CREAT_STRING_FunctionM]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CREAT_STRING_FunctionM]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CREAT_STRING_SETCOL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CREAT_STRING_SETCOL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CREAT_STRING_Sys_DictTable]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CREAT_STRING_Sys_DictTable]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_BETWEEN_CURR_YYYYMM]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_BETWEEN_CURR_YYYYMM]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_BILL_XuHao_ChongPai]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_BILL_XuHao_ChongPai]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_BillFlow_insert_YYYYMM]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_BillFlow_insert_YYYYMM]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_CACULATOR_YYYYMM ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_CACULATOR_YYYYMM ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_DataToNext]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_DataToNext]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_DataToNextDel]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_DataToNextDel]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_Data_START]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_Data_START]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_Data_START_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_Data_START_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_DengZhang]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_DengZhang]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_DengZhang_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_DengZhang_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_GET_ItemInfo_ItemBM]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_GET_ItemInfo_ItemBM]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_GET_Next_Item_len]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_GET_Next_Item_len]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_GET_SUM]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_GET_SUM]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_GongShiZhiXing]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_GongShiZhiXing]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_INOUTMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_INOUTMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_JieZhuanSY]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_JieZhuanSY]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_KeMuYuEHZB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_KeMuYuEHZB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_LRBMB_CRAET_CW_LRB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_LRBMB_CRAET_CW_LRB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_LRB_JiSuan]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_LRB_JiSuan]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_RJZINOUTMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_RJZINOUTMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_ShiSuanPHB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_ShiSuanPHB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_UpdateCW_INITBALAtotal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_UpdateCW_INITBALAtotal]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_XJLLBMB_CRAET_CW_XJLLB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_XJLLBMB_CRAET_CW_XJLLB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_XJLLB_JiSuan]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_XJLLB_JiSuan]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_XianJinLLFP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_XianJinLLFP]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_ZCFZBMB_CRAET_CW_ZCFZB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_ZCFZBMB_CRAET_CW_ZCFZB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_ZCFZB_JiSuan]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_ZCFZB_JiSuan]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_ZongFenLeiZhang]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_ZongFenLeiZhang]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Check_BILL_NO]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Check_BILL_NO]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Check_Cred_Code_NO]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Check_Cred_Code_NO]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DANJuXiaoShu_SET]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[DANJuXiaoShu_SET]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DetailBillFlow_insert_YYYYMM]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[DetailBillFlow_insert_YYYYMM]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FYKZBILLTREE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FYKZBILLTREE]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETALLPRICE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETALLPRICE]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETCLIENTIDEAMOUNT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETCLIENTIDEAMOUNT]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETGOODSIDEQTY]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETGOODSIDEQTY]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETGOODSIDMEQTY]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETGOODSIDMEQTY]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETGOODSSQL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETGOODSSQL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETGoodsIDEQTYANDALL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETGoodsIDEQTYANDALL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETKEYCodeKEYVALUE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETKEYCodeKEYVALUE]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETKEYVALUE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETKEYVALUE]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETKEYVALUE00]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETKEYVALUE00]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETKEYVALUE4]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETKEYVALUE4]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETVENDORIDEAMOUNT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETVENDORIDEAMOUNT]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETXSPrice]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETXSPrice]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETXSPriceDays]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETXSPriceDays]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GET_APRICE ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GET_APRICE ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GET_BILL_NO]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GET_BILL_NO]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GET_CURR_YYYYMM_FlagPost]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GET_CURR_YYYYMM_FlagPost]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GET_CWPZ_BILLID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GET_CWPZ_BILLID]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GET_CW_initbala_PingHeng]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GET_CW_initbala_PingHeng]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GET_Cred_Code_NO]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GET_Cred_Code_NO]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GET_EPRICE ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GET_EPRICE ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GET_GoodsTypeNew_PrevNO]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GET_GoodsTypeNew_PrevNO]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GET_ItemInfo_ItemBM]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GET_ItemInfo_ItemBM]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GET_MQTY_EQTY_2011]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GET_MQTY_EQTY_2011]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETwb_py_FIRST]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETwb_py_FIRST]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODSCGDDMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GOODSCGDDMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODSCGRKMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GOODSCGRKMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODSGJRKMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GOODSGJRKMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODSGJRKYYYYMMDD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GOODSGJRKYYYYMMDD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODSNAME_CF]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GOODSNAME_CF]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODSXSCKMLRMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GOODSXSCKMLRMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODSXSCKMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GOODSXSCKMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODSXSDDMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GOODSXSDDMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODS_STOREMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GOODS_STOREMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Get_Max_Min_Date]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Get_Max_Min_Date]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[INSERTTOSecurity]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[INSERTTOSecurity]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QTSRBILLTREE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QTSRBILLTREE]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SM_DataToNext]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[SM_DataToNext]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SM_DataToNextDel]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[SM_DataToNextDel]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SM_Data_START]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[SM_Data_START]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STOREINOUTMXBREP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STOREINOUTMXBREP]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORELEDGER]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORELEDGER]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORELEDGER_BJ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORELEDGER_BJ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORELEDGER_BJ_Creat_CGDD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORELEDGER_BJ_Creat_CGDD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORELEDGER_CRAET_PD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORELEDGER_CRAET_PD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORELEDGER_XIAN]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORELEDGER_XIAN]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STOREYYYYMMDD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STOREYYYYMMDD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CGDD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CGDD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CGDD_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CGDD_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CGFK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CGFK]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CGFK_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CGFK_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CGFP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CGFP]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CGFP_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CGFP_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CGRK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CGRK]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CGRK_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CGRK_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CGTH]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CGTH]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CGTH_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CGTH_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CKDB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CKDB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CKDB_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CKDB_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CKPD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CKPD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CKPD_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CKPD_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CSH]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CSH]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CSH_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CSH_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CW_PingZheng]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CW_PingZheng]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CW_PingZheng_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CW_PingZheng_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_Calculate_Aprice]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_Calculate_Aprice]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_FYKZ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_FYKZ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_FYKZ_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_FYKZ_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_GJRK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_GJRK]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_GJRK_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_GJRK_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_GJRK_DEL_CGRK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_GJRK_DEL_CGRK]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_INVOICE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_INVOICE]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_INVOICE_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_INVOICE_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_JGD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_JGD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_JGD_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_JGD_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_LIUH]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_LIUH]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_LIUH_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_LIUH_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_MOVE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_MOVE]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_MOVE_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_MOVE_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_QGAD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_QGAD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_QGAD_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_QGAD_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_QGD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_QGD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_QGD_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_QGD_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_QTCK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_QTCK]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_QTCK_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_QTCK_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_QTRK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_QTRK]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_QTRK_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_QTRK_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_QTSR]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_QTSR]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_QTSR_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_QTSR_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_SUM_ALL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_SUM_ALL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_TALLY]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_TALLY]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_TALLY_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_TALLY_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_XSCK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_XSCK]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_XSCK_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_XSCK_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_XSDD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_XSDD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_XSDD_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_XSDD_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_XSFP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_XSFP]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_XSFP_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_XSFP_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_XSSK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_XSSK]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_XSSK_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_XSSK_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_XSTH]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_XSTH]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_XSTH_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_XSTH_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_YYYYMM_INSERT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_YYYYMM_INSERT]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_YunFeiFK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_YunFeiFK]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_YunFeiFK_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_YunFeiFK_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_ZCD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_ZCD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_ZCD_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_ZCD_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_ZFD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_ZFD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_ZFD_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_ZFD_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Store_Yue_JiSuan]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Store_Yue_JiSuan]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UPDATE_DATA]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[UPDATE_DATA]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Update_GoodsTypeNew_fullname]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Update_GoodsTypeNew_fullname]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Update_GoodsTypeNew_fullname_ALL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Update_GoodsTypeNew_fullname_ALL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Update_Iteminfo_fullname]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Update_Iteminfo_fullname]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Update_Iteminfo_fullname_ALL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Update_Iteminfo_fullname_ALL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VENDORCGDDMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[VENDORCGDDMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VENDORCGRKMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[VENDORCGRKMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VENDORGJRKMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[VENDORGJRKMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VENDORGJRKYYYYMMDD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[VENDORGJRKYYYYMMDD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VENDORINOUTMXBREP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[VENDORINOUTMXBREP]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VENDORYYYYMMDD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[VENDORYYYYMMDD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VENDOR_CACULATOR_YYYYMM ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[VENDOR_CACULATOR_YYYYMM ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[YYYYMMPOSTBILL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[YYYYMMPOSTBILL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[YunShuDWINOUTMXBREP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[YunShuDWINOUTMXBREP]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[YunShuDWYYYYMMDD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[YunShuDWYYYYMMDD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[YunShuDW_CACULATOR_YYYYMM ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[YunShuDW_CACULATOR_YYYYMM ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[initialCW_initbala]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[initialCW_initbala]
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG









--------------------------------------------------------------------
--Create by li fa zheng  2004/07/01              
--    再版1：   2004-07-02        
----    功能：    分仓库核算单价
--
--
--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[APRICECACULATOR_STORE ]  (@GOODSID  varchar(30),@STOREID00  varchar(30),
@YYYYMM  varchar(6)    )  --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 
declare @INOUTFLAG NUMERIC(20,10)
declare @BQTY NUMERIC(20,10)
declare @BPRICE NUMERIC(20,10)
declare @INQTY NUMERIC(20,10)
declare @MINQTY NUMERIC(20,10)
declare @MEQTY NUMERIC(20,10)
declare @INQTYSUM NUMERIC(20,10)
declare @INAMOUNTSUM  NUMERIC(20,10)
declare @INPRICE NUMERIC(20,10)
declare @EQTY NUMERIC(20,10)
declare @EPRICE NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)

declare @NEWEQTY NUMERIC(20,10)
declare @MNEWEQTY NUMERIC(20,10)
declare @NEWEPRICE NUMERIC(20,10)
declare @NEWEAMOUNT NUMERIC(20,10)

declare @SUMBAMOUNT NUMERIC(20,10)            ---本期期初总金额
declare @SUMBQTY NUMERIC(20,10)                    ---本期期初总数量
declare @MSUMBQTY NUMERIC(20,10)                    ---本期期初总数量
declare @SUMBPRICE NUMERIC(20,10)                 ---本期期初加权价
declare @DBPRICE    NUMERIC(20,10)                 ---本期期初加权价

declare @ID varchar(22)           --单号

declare @INF_COSTINGTYPEID  INT                ---本期期初加权价

declare @ITEMNO varchar(15)               --明细存货编号
declare @BILLID varchar(22)           --单号

declare @BILLTYPE INT


 
BEGIN

	       ----解决总仓库存的问题   BEGIN
	            if not exists(select *  from GOODSINIT  where 
	                                                 (rtrim(GOODSID) = @GOODSID AND  (rtrim(STOREID) = @STOREID00) )
             		                                 and(rtrim(YYYYMM) = @YYYYMM)
             		                                 )       
	           BEGIN
		    insert into GOODSINIT 
		    (GOODSID,YYYYMM,STOREID,
		     BQTY,BPRICE,INQTY,OUTQTY,
		     EQTY,EPRICE,BAMOUNT,EAMOUNT	     )
		    Values
		    (@GOODSID,@YYYYMM,@STOREID00,
		     0,0,0,0,
		     0,0,0,0)    

	           END      ------IF   END
                     ----解决总仓库存的问题 END
------------------------------------------------------------------------------------
  	            select    @SUMBAMOUNT=isnull(BAMOUNT,0),@SUMBQTY=isnull(BQTY,0),@MSUMBQTY=isnull(MBQTY,0),
					@SUMBPRICE=isnull(BPRICE,0)   FROM  GOODSINIT  
             	                                    where    (rtrim(GOODSID) = @GOODSID)    and (rtrim(YYYYMM) = @YYYYMM)  AND  (rtrim(STOREID) = @STOREID00) 
                                       -------以上是期初数据

       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID

        IF    @INF_COSTINGTYPEID=3      ----------- IF    @INF_COSTINGTYPEID=3       BEGIN    全月平均一次计算价格
        BEGIN
                         select    @INQTYSUM =  SUM(INQTY),  @INAMOUNTSUM =  SUM(INQTY*INPRICE)   FROM DetailBillFlow
			where (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   AND  (rtrim(STOREID) = @STOREID00)   and   ( YYYYMMBILL=1   )  AND ( INOUTFLAG = 1)   AND BILLTYPE<>6   AND BILLTYPE<>12
                                          ------------以上是本期合计   不包括调拨单的部分
             		  if (@SUMBAMOUNT is null) 
		     set  @SUMBAMOUNT=0
		  if (@SUMBQTY is null)   
			set @SUMBQTY=0
		  if (@SUMBPRICE is null)   
			set @SUMBPRICE=0
		  if (@INAMOUNTSUM is null)   
			set @INAMOUNTSUM=0
		  if (@INQTYSUM is null)   
			set @INQTYSUM=0

                         SET      @INAMOUNTSUM = @SUMBAMOUNT+@INAMOUNTSUM
                         SET      @INQTYSUM = @SUMBQTY+@INQTYSUM
		  if (-0.0000001<@INQTYSUM and @INQTYSUM<0.0000001)
		  begin
		   set   @INQTYSUM=0
		  end 
		 IF  @INQTYSUM<>0
		  begin
                             SET      @SUMBPRICE=ROUND(@INAMOUNTSUM/ @INQTYSUM,6)
		  end 


	          UPDATE   DETAILBILLFLOW  set    INPRICE= @SUMBPRICE
                         where (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=1   )  AND  (rtrim(STOREID) = @STOREID00)  AND ( INOUTFLAG = -1  OR  BILLTYPE = 5   OR   BILLTYPE = 6  OR BILLTYPE = 12 )
        END     ----------- IF    @INF_COSTINGTYPEID=3       END    全月平均一次计算价格   特别处理盘点和调拨
----------------------------------------------------------------
        IF   ( @INF_COSTINGTYPEID=1) OR   ( @INF_COSTINGTYPEID=3)    ----------- IF    @INF_COSTINGTYPEID=1 和 ( @INF_COSTINGTYPEID=3)      BEGIN     移动加权方式
        BEGIN
	       ---------注意是分仓库核算成本价格，每个仓库数量都是不同的！
                    ---------移动加权、全月一次平均以及个别指定算法都是一样的（基本一样，不同之处以上部分就是）
	    declare APRICE_STORE Cursor READ_ONLY for Select ID, GOODSID ,
             		     isnull(INQTY,0) as INqty,isnull(INPRICE,0) as INPRICE ,
             		     isnull(EQTY,0) as EQTY , isnull(EPRICE,0) as EPRICE , INOUTFLAG,
		      isnull(EAMOUNT,0) as EAMOUNT ,BILLTYPE,ITEMNO,BILLID,
		       isnull(MINQTY,0) as MINqty,  isnull(MEQTY,0) as MEqty
---	                  from DetailBillFlow   where (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=1   )  AND  (rtrim(STOREID) = @STOREID00) 
	                  from DetailBillFlow   where (rtrim(YYYYMM) >= @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=1   )  AND  (rtrim(STOREID) = @STOREID00) 
             		      ORDER BY BILLDATE,ID

	    Open APRICE_STORE

	    fetch APRICE_STORE into @ID,@GOODSID,@INqty,@INPRICE,@Eqty,@EPRICE,@INOUTFLAG,@EAMOUNT, @BILLTYPE,@ITEMNO,@BILLID,@MINQTY,@MEQTY


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	         IF (@INOUTFLAG=1)   and (@BILLTYPE<>5)  and  (@BILLTYPE<>6)   and  (@BILLTYPE<>12) 
	         BEGIN
	          Select @NEWEqty=NEWQTY,@MNEWEqty=MNEWQTY,@NEWEPRICE=NEWPRICE,@NEWEAMOUNT=NEWAMOUNT
             		       from  APRICECACULATOR    (@SUMBQTY,@MSUMBQTY,@SUMBPRICE,@SUMBAMOUNT,@INqty,@MINqty,@INPRICE,@INOUTFLAG)
	             ---定义的函数APRICECACULATOR
	          UPDATE   DETAILBILLFLOW  set    EQTY=@NEWEQTY,MEQTY=@MNEWEQTY,EPRICE=@NEWEPRICE,EAMOUNT=@NEWEAMOUNT
             		          WHERE ID=@ID
	         END
	         IF ( @INOUTFLAG = -1   )         OR  (@INOUTFLAG = 1  AND @BILLTYPE = 6)     OR  (@INOUTFLAG = 1  AND @BILLTYPE = 12)  
	         BEGIN
	             ---定义的函数APRICECACULATOR
	                       if  (@INF_COSTINGTYPEID=1)
                                    BEGIN 
		          Select @NEWEqty=NEWQTY,@MNEWEqty=MNEWQTY,@NEWEPRICE=NEWPRICE,@NEWEAMOUNT=NEWAMOUNT
             			       from  APRICECACULATOR    (@SUMBQTY,@MSUMBQTY,@SUMBPRICE,@SUMBAMOUNT,@INqty,@MINqty,@SUMBPRICE,@INOUTFLAG)
		          UPDATE   DETAILBILLFLOW  set    EQTY=@NEWEQTY,MEQTY=@MNEWEQTY,EPRICE=@NEWEPRICE,EAMOUNT=@NEWEAMOUNT,INPRICE=@SUMBPRICE
             			          WHERE ID=@ID
                                    END
	                       if   @INF_COSTINGTYPEID=3
                                    BEGIN 
		          Select @NEWEqty=NEWQTY,@MNEWEqty=MNEWQTY,@NEWEPRICE=NEWPRICE,@NEWEAMOUNT=NEWAMOUNT
             			       from  APRICECACULATOR    (@SUMBQTY,@MSUMBQTY,@SUMBPRICE,@SUMBAMOUNT,@INqty,@MINqty,@INPRICE,@INOUTFLAG)
		          UPDATE   DETAILBILLFLOW  set    EQTY=@NEWEQTY, MEQTY=@MNEWEQTY,EPRICE=@NEWEPRICE,EAMOUNT=@NEWEAMOUNT
             			          WHERE ID=@ID
                                    END

	         END
	         IF    (@INOUTFLAG = 1)  AND (@BILLTYPE=5)    
	         BEGIN
	             ---定义的函数APRICECACULATOR
	                       if  (@INF_COSTINGTYPEID=1)  OR(  @INF_COSTINGTYPEID=3)
                                    BEGIN 
			SELECT @DBPRICE=(SELECT INPRICE FROM DetailBillFlow  WHERE YYYYMMBILL=1 AND BILLTYPE=5  AND BILLID=@BILLID  AND GOODSID=@GOODSID AND ITEMNO=@ITEMNO  AND INOUTFLAG=-1 )
		          Select @NEWEqty=NEWQTY,@MNEWEqty=MNEWQTY,@NEWEPRICE=NEWPRICE,@NEWEAMOUNT=NEWAMOUNT
             			       from  APRICECACULATOR    (@SUMBQTY,@MSUMBQTY,@SUMBPRICE,@SUMBAMOUNT,@INqty,@MINqty,@DBPRICE,@INOUTFLAG)
		          UPDATE   DETAILBILLFLOW  set    EQTY=@NEWEQTY, MEQTY=@MNEWEQTY,EPRICE=@NEWEPRICE,EAMOUNT=@NEWEAMOUNT,INPRICE=@DBPRICE
             			          WHERE ID=@ID
                                    END
	         END
	        set    @SUMBQTY=@NEWEqty
	        set    @MSUMBQTY=@MNEWEqty
	        set    @SUMBPRICE=@NEWEPRICE
	        set    @SUMBAMOUNT=@NEWEAMOUNT

	    fetch APRICE_STORE into @ID,@GOODSID,@INqty,@INPRICE,@Eqty,@EPRICE,@INOUTFLAG,@EAMOUNT, @BILLTYPE,@ITEMNO,@BILLID,@MINQTY,@MEQTY
 
	            update   GOODS   SET APRICE = @NEWEPRICE WHERE  GOODSID=@GOODSID

	    END           ------- APRICE_STORE  WHILE

	    close APRICE_STORE
	    deallocate APRICE_STORE

        END              -------------------        IF    @INF_COSTINGTYPEID=1    和 ( @INF_COSTINGTYPEID=3)     END
-----------------------------------------------------------------------------------------------------------------------------------------------------------


END



----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG







































--------------------------------------------------------------------
--Create by li fa zheng  2012/09/01              
--功能： 本会计期间核算先进先出成本
--
--
--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[APRICECACULATOR_STORE_XIAN ]  (@GOODSID  varchar(30),@STOREID00  varchar(30),
@YYYYMM  varchar(6)    )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 
declare @INOUTFLAG NUMERIC(20,6)
declare @BQTY NUMERIC(20,6)
declare @BPRICE NUMERIC(20,6)
declare @INQTY NUMERIC(20,6)
declare @INQTYSUM NUMERIC(20,6)
declare @INAMOUNTSUM  NUMERIC(20,6)
declare @INPRICE NUMERIC(20,6)
declare @EQTY NUMERIC(20,6)
declare @EPRICE NUMERIC(20,6)
declare @EAMOUNT NUMERIC(20,6)

declare @NEWEQTY NUMERIC(20,6)
declare @NEWEPRICE NUMERIC(20,6)
declare @NEWEAMOUNT NUMERIC(20,6)
declare @OUTAMOUNT NUMERIC(20,6)

declare @SUMBAMOUNT NUMERIC(20,6)            ---本期期初总金额
declare @SUMBQTY NUMERIC(20,6)                    ---本期期初总数量
declare @MSUMBQTY NUMERIC(20,6)                    ---本期期初总数量
declare @OUTQTY NUMERIC(20,6)                    ---本期期初总数量
declare @OUTMQTY NUMERIC(20,6)                    ---本期期初总数量
declare @KeYongQTY NUMERIC(20,6)                    ---本期期初总数量
declare @KeYongMQTY NUMERIC(20,6)                    ---本期期初总数量
declare @KeYongAMOUNT NUMERIC(20,6)                    ---本期期初总数量
declare @KeYongPrice NUMERIC(20,6)                    ---本期期初总数量
declare @TMPKeYongQTY NUMERIC(20,6)                    ---本期期初总数量
declare @TMPKeYongMQTY NUMERIC(20,6)                    ---本期期初总数量
declare @TMPKeYongAMOUNT NUMERIC(20,6)                    ---本期期初总数量
declare @TMPKeYongPrice NUMERIC(20,6)                    ---本期期初总数量
declare @TMPQTY NUMERIC(20,6)                    ---本期期初总数量
declare @TMPMQTY NUMERIC(20,6)                    ---本期期初总数量
declare @MINQTY NUMERIC(20,10)
declare @MEQTY NUMERIC(20,10)
declare @MNEWEqty NUMERIC(20,10)


declare @SUMBPRICE NUMERIC(20,6)                 ---本期期初加权价

declare @INF_COSTINGTYPEID  INT                ---本期期初加权价

declare @ITEMNO varchar(15)               --明细存货编号
declare @MINbilldate  datetime   
declare @Billdate  datetime   


declare @BILLID varchar(22)           --单号
declare @StoreID varchar(22)           --单号

declare @BILLTYPE INT

declare @ID varchar(50)           --单号
declare @KeYongID varchar(50)           --单号

 
BEGIN

------------------------------------------------------------------------------------
          SELECT   @SUMBAMOUNT=(SELECT    isnull(SUM(BAMOUNT),0)  FROM  DetailBillFlow     where    (rtrim(GOODSID) = @GOODSID)    and (rtrim(YYYYMM) = @YYYYMM)      AND  YYYYMMBILL=0   AND  (rtrim(STOREID) = @STOREID00) )
          SELECT   @SUMBQTY=(SELECT    isnull(SUM(BQTY),0)   FROM  DetailBillFlow     where    (rtrim(GOODSID) = @GOODSID)    and (rtrim(YYYYMM) = @YYYYMM)     AND  YYYYMMBILL=0  AND  (rtrim(STOREID) = @STOREID00) )
          SELECT   @MSUMBQTY=(SELECT    isnull(SUM(MBQTY),0)   FROM  DetailBillFlow     where    (rtrim(GOODSID) = @GOODSID)    and (rtrim(YYYYMM) = @YYYYMM)     AND  YYYYMMBILL=0  AND  (rtrim(STOREID) = @STOREID00) )


                          IF    @SUMBQTY<>0
                          BEGIN
		SELECT   @SUMBPRICE=@SUMBAMOUNT/@SUMBQTY
		END
                           ELSE
                          BEGIN
		SELECT   @SUMBPRICE=0
		END
                                       -------以上是期初数据

       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID

        IF   @INF_COSTINGTYPEID=6   ----------- IF    @INF_COSTINGTYPEID=1 和 ( @INF_COSTINGTYPEID=3)      BEGIN     移动加权方式
        BEGIN
	       ---------注意是分仓库核算成本价格，每个仓库数量都是不同的！
                    ---------移动加权、全月一次平均以及个别指定算法都是一样的（基本一样，不同之处以上部分就是）

		---算法设计，先核算出库单价

------------------恢复本会计期间的可用数量

/*		update DetailBillFlow set EQTY=StoreEqty,Eprice=STOREEPrice,EAMOUNT=StoreEAMOUNT
				 where (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2   )
						 AND INOUTFLAG = 1   
						 AND  (rtrim(STOREID) = @STOREID00) 

*/

		update DetailBillFlow set EQTY=INQTY,MEQTY=MINQTY,Eprice=INPRICE,EAMOUNT=INQTY*INPRICE
				 where (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2   )
						 AND INOUTFLAG = 1   
						 AND  (rtrim(STOREID) = @STOREID00) 
             		     


	    declare APRICE_TEMP Cursor READ_ONLY for Select ID, GOODSID ,StoreID,
             		     isnull(INQTY,0) as INqty,isnull(INPRICE,0) as INPRICE ,
             		     isnull(EQTY,0) as EQTY , isnull(EPRICE,0) as EPRICE , INOUTFLAG, isnull(EAMOUNT,0) as EAMOUNT ,
				BILLTYPE,BILLID,BILLDATE,
		       isnull(MINQTY,0) as MINqty,  isnull(MEQTY,0) as MEqty
	                  from DetailBillFlow   where (rtrim(YYYYMM) >= @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=1   )
						 AND  (rtrim(STOREID) = @STOREID00) 
             		      ORDER BY BILLDATE,ID

	    Open APRICE_TEMP

	    fetch APRICE_TEMP into @ID,@GOODSID,@StoreID,@INqty,@INPRICE,@Eqty,@EPRICE,@INOUTFLAG,@EAMOUNT, @BILLTYPE,@BILLID,@Billdate,@MINQTY,@MEQTY


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	         IF (@INOUTFLAG=1)   AND  (@BILLTYPE<>216)
	         BEGIN

			IF   @BILLTYPE=6
			BEGIN
				Select @INPRICE=@SUMBPRICE
			END
			 
		          Select @NEWEqty=NEWQTY,@MNEWEqty=MNEWQTY,@NEWEPRICE=NEWPRICE,@NEWEAMOUNT=NEWAMOUNT
	             	       from  APRICECACULATOR    (@SUMBQTY,@MSUMBQTY,@SUMBPRICE,@SUMBAMOUNT,@INqty,@MINqty,@INPRICE,@INOUTFLAG)
	             ---定义的函数APRICECACULATOR
	        	  UPDATE   DETAILBILLFLOW  set    EQTY=@NEWEQTY,MEQTY=@MNEWEQTY,EPRICE=@NEWEPRICE,EAMOUNT=@NEWEAMOUNT
             		          WHERE ID=@ID


			IF   @BILLTYPE=6
			BEGIN
		          UPDATE   DETAILBILLFLOW  set   INPRICE=@INPRICE
             		           WHERE ID=@ID

		          UPDATE   DETAILBILLFLOW  set   INPRICE=@INPRICE,EPRICE=@INPRICE,EAMOUNT=INQTY*@INPRICE
					where (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2   )
						 AND  (rtrim(STOREID) = @STOREID00)  AND BILLTYPE=6 AND BILLID=@BILLID
			END

--			print @NEWEQTY
	         END
	         IF ( @INOUTFLAG = -1   )  OR  (@INOUTFLAG = 1  AND @BILLTYPE=7)  
	         BEGIN

		         IF    (@BILLTYPE<>216)   
		         BEGIN

			----在这里先计算出库单价
			----	逐行提取
				set @OUTQTY=@INqty
				set @OUTMQTY=@MINqty
				set @KeYongQTY=0
				set @KeYongMQTY=0
				set @KeYongPrice=0
				set @KeYongAMOUNT=0

				if @BILLTYPE =7         -----处理采购退货单
				begin
				set @OUTQTY=-@INqty
				set @OUTMQTY=-@MINqty
				end
			

				while @OUTQTY>0
				begin
					

				print @OUTQTY

					select  @MINBILLDATE=MIN(BILLDATE) from DETAILBILLFLOW where Eqty > 0 and 
					  (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2 )
								 AND  (rtrim(STOREID) = @STOREID00)  

					select @KeYongID=min(ID) from DETAILBILLFLOW where Eqty > 0 and 
					  (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2 )
								 AND  (rtrim(STOREID) = @STOREID00)  AND  BILLDATE=@MinBILLDATE  
------假设存在的情况下
					select @TMPKeYongQTY=Eqty,@TMPKeYongMQTY=MEqty,@TMPKeyongPrice=Eprice,@TMPKeYongAMOUNT=EQTY*EPrice from DETAILBILLFLOW where ID=@KeYongID
					print @TMPKeYongQTY

					set @TMPQTY=@TMPKeYongQTY-@OUTQTY
					set @TMPMQTY=@TMPKeYongMQTY-@OUTMQTY
					if @TMPQTY<=0
					begin
					set @KeYongAMOUNT=@KeYongAMOUNT+@TMPKeYongAMOUNT
					update DETAILBILLFLOW set EQTY=0,MEQTY=0,EAMOUNT=0 where ID=@KeYongID
					set @OUTQTY=@OUTQTY-@TMPKeYongQTY
					set @OUTMQTY=@OUTMQTY-@TMPKeYongMQTY

					end
					else
					begin
					set @KeYongAMOUNT=@KeYongAMOUNT+@OUTQTY*@TMPKeyongPrice
					update DETAILBILLFLOW set EQTY=EQTY-@OUTQTY,MEQTY=MEQTY-@OUTMQTY where ID=@KeYongID
				print @KeYongID

					set @OUTQTY=@OUTQTY-@TMPKeYongQTY
					set @OUTMQTY=@OUTMQTY-@TMPKeYongMQTY
					end

				end     
			    
				if @INqty<>0 
				begin
					set @KeYongPrice=(@KeYongAMOUNT/@INqty)
				end

				if @BILLTYPE =7  and  @INqty<>0       -----处理采购退货单
				begin
				set @KeYongPrice=-(@KeYongAMOUNT/@INqty)
				end
			

				print @KeYongPrice
				
		          UPDATE   DETAILBILLFLOW  set    INPRICE=@KeYongPrice  WHERE ID=@ID

		          Select @NEWEqty=NEWQTY,@MNEWEqty=MNEWQTY,@NEWEPRICE=NEWPRICE,@NEWEAMOUNT=NEWAMOUNT
             			       from  APRICECACULATOR    (@SUMBQTY,@MSUMBQTY,@SUMBPRICE,@SUMBAMOUNT,@INqty,@MINqty,@KeYongPrice ,@INOUTFLAG)
		          UPDATE   DETAILBILLFLOW  set    EQTY=@NEWEQTY,MEQTY=@MNEWEQTY,EPRICE=@NEWEPRICE,EAMOUNT=@NEWEAMOUNT
             			          WHERE ID=@ID
		         END
	         END

-----------------------------------------------------
	         IF ( @INOUTFLAG = -1) AND (@BILLTYPE in (12,216)) 
	         BEGIN

--------------------------负数的处理

			----在这里先计算出库单价
			----	逐行提取
				set @OUTQTY=@INqty
				set @OUTMQTY=@MINqty
				set @KeYongQTY=0
				set @KeYongMQTY=0
				set @KeYongPrice=0
				set @KeYongAMOUNT=0

				set @OUTQTY=-@INqty
				set @OUTMQTY=-@MINqty
			

				while @OUTQTY>0
				begin
					

				print @OUTQTY
--------------------------------------销售退货、与退料单寻单价入库

					select  @MINBILLDATE=MIN(BILLDATE) from DETAILBILLFLOW where Eqty > 0 
						and INQTY>Eqty  AND
					  (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2 )
								 AND  (rtrim(STOREID) = @STOREID00)  

					select @KeYongID=MIN(ID) from DETAILBILLFLOW where Eqty > 0 
						and INQTY>Eqty AND
					  (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2 )
								 AND  (rtrim(STOREID) = @STOREID00)  AND  BILLDATE=@MinBILLDATE  
------假设存在的情况下
					select @TMPKeYongQTY=INQTY-Eqty,@TMPKeYongMQTY=MINQTY-MEqty,@TMPKeyongPrice=Eprice,@TMPKeYongAMOUNT=(INQTY-Eqty)*EPrice from DETAILBILLFLOW where ID=@KeYongID
					print @TMPKeYongQTY

					set @TMPQTY=@OUTQTY-@TMPKeYongQTY
					set @TMPMQTY=@OUTMQTY-@TMPKeYongMQTY
					if @TMPQTY>=0
					begin
					set @KeYongAMOUNT=@KeYongAMOUNT+@TMPKeYongQTY*@TMPKeyongPrice
					update DETAILBILLFLOW set EQTY=INQTY,MEQTY=MINQTY where ID=@KeYongID
					set @OUTQTY=@OUTQTY-@TMPKeYongQTY
					set @OUTMQTY=@OUTMQTY-@TMPKeYongMQTY
					end
					else
					begin
				print @KeYongID
					set @KeYongAMOUNT=@KeYongAMOUNT+@OUTQTY*@TMPKeyongPrice
					update DETAILBILLFLOW set EQTY=EQTY+@OUTQTY,MEQTY=MEQTY+@OUTMQTY where ID=@KeYongID
					set @OUTQTY=@OUTQTY-@TMPKeYongQTY
					set @OUTMQTY=@OUTMQTY-@TMPKeYongMQTY


					end

				end     
			    
----				set @KeYongPrice=(@KeYongAMOUNT/@INqty)

				set @KeYongPrice=-(@KeYongAMOUNT/@INqty)
			

				
		          UPDATE   DETAILBILLFLOW  set    INPRICE=@KeYongPrice  WHERE ID=@ID

		          Select @NEWEqty=NEWQTY,@MNEWEqty=MNEWQTY,@NEWEPRICE=NEWPRICE,@NEWEAMOUNT=NEWAMOUNT
             			       from  APRICECACULATOR    (@SUMBQTY,@MSUMBQTY,@SUMBPRICE,@SUMBAMOUNT,@INqty,@MINqty,@KeYongPrice ,@INOUTFLAG)
		          UPDATE   DETAILBILLFLOW  set    EQTY=@NEWEQTY,MEQTY=@MNEWEQTY,EPRICE=@NEWEPRICE,EAMOUNT=@NEWEAMOUNT
             			          WHERE ID=@ID

	         END
--------------------------------------------------------------------

	        set    @SUMBQTY=@NEWEqty
	        set    @MSUMBQTY=@MNEWEqty
	        set    @SUMBPRICE=@NEWEPRICE
	        set    @SUMBAMOUNT=@NEWEAMOUNT

	    fetch APRICE_TEMP into @ID,@GOODSID,@StoreID,@INqty,@INPRICE,@Eqty,@EPRICE,@INOUTFLAG,@EAMOUNT, @BILLTYPE,@BILLID,@Billdate,@MINQTY,@MEQTY
 
	            update   GOODS   SET APRICE = @NEWEPRICE WHERE  GOODSID=@GOODSID

	    END           ------- APRICE_TEMP  WHILE

	    close APRICE_TEMP
	    deallocate APRICE_TEMP

-----------------////
		update DetailBillFlow set EAMOUNT=EQTY*INPRICE
				 where (rtrim(YYYYMM) >= @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2   )
						 AND INOUTFLAG = 1   
						 AND  (rtrim(STOREID) = @STOREID00) 




        END              -------------------        IF    @INF_COSTINGTYPEID=1    和 ( @INF_COSTINGTYPEID=3)     END
-----------------------------------------------------------------------------------------------------------------------------------------------------------


END




















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG















--------------------------------------------------------------------
--Create by li fa zheng  2004/07/01              
--    再版1：   2004-07-02        
--     功能： 本会计期间核算成本价
--
--
--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[APRICECACULATOR_YYYYMM ]  (@GOODSID  varchar(30),@STOREID00  varchar(30),
@YYYYMM  varchar(6)    )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 
declare @INOUTFLAG NUMERIC(20,10)
declare @BQTY NUMERIC(20,10)
declare @BPRICE NUMERIC(20,10)
declare @INQTY NUMERIC(20,10)
declare @MINQTY NUMERIC(20,10)
declare @INQTYSUM NUMERIC(20,10)
declare @INAMOUNTSUM  NUMERIC(20,10)
declare @INPRICE NUMERIC(20,10)
declare @EQTY NUMERIC(20,10)
declare @MEQTY NUMERIC(20,10)
declare @EPRICE NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)

declare @NEWEQTY NUMERIC(20,10)
declare @MNEWEQTY NUMERIC(20,10)
declare @NEWEPRICE NUMERIC(20,10)
declare @NEWEAMOUNT NUMERIC(20,10)

declare @SUMBAMOUNT NUMERIC(20,10)            ---本期期初总金额
declare @SUMBQTY NUMERIC(20,10)                    ---本期期初总数量
declare @MSUMBQTY NUMERIC(20,10)                    ---本期期初总数量
declare @SUMBPRICE NUMERIC(20,10)                 ---本期期初加权价

declare @INF_COSTINGTYPEID  INT                ---本期期初加权价

declare @ITEMNO varchar(15)               --明细存货编号


declare @BILLID varchar(22)           --单号
declare @ID varchar(22)           --单号

declare @BILLTYPE INT




 
BEGIN

	       ----解决总仓库存的问题   BEGIN
	            if not exists(select *  from GOODSINIT  where 
	                                                 (rtrim(GOODSID) = @GOODSID)
             		                                 and(rtrim(YYYYMM) = @YYYYMM AND  (rtrim(STOREID) = @STOREID00) )
             		                                 )       
	           BEGIN
		    insert into GOODSINIT 
		    (GOODSID,YYYYMM,STOREID,
		     BQTY,BPRICE,INQTY,OUTQTY,
		     EQTY,EPRICE,BAMOUNT,EAMOUNT	     )
		    Values
		    (@GOODSID,@YYYYMM,@STOREID00,
		     0,0,0,0,
		     0,0,0,0)    

	           END      ------IF   END
                     ----解决总仓库存的问题 END
------------------------------------------------------------------------------------
                          SELECT   @SUMBAMOUNT=(SELECT    isnull(SUM(BAMOUNT),0)  FROM  GOODSINIT    where    (rtrim(GOODSID) = @GOODSID)    and (rtrim(YYYYMM) = @YYYYMM)     )
                          SELECT   @SUMBQTY=(SELECT    isnull(SUM(BQTY),0)  FROM  GOODSINIT    where    (rtrim(GOODSID) = @GOODSID)    and (rtrim(YYYYMM) = @YYYYMM)     )
                          SELECT   @MSUMBQTY=(SELECT    isnull(SUM(MBQTY),0)  FROM  GOODSINIT    where    (rtrim(GOODSID) = @GOODSID)    and (rtrim(YYYYMM) = @YYYYMM)     )
                          IF    @SUMBQTY<>0
                          BEGIN
		SELECT   @SUMBPRICE=@SUMBAMOUNT/@SUMBQTY
		END
                           ELSE
                          BEGIN
		SELECT   @SUMBPRICE=0
		END
                                       -------以上是期初数据

       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID

        IF    @INF_COSTINGTYPEID=3      ----------- IF    @INF_COSTINGTYPEID=3       BEGIN    全月平均一次计算价格
        BEGIN
                         select    @INQTYSUM =  SUM(INQTY), @INAMOUNTSUM =  SUM(INQTY*INPRICE)   FROM DetailBillFlow
			where (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=1   )  AND( INOUTFLAG = 1)    AND BILLTYPE<>5   AND BILLTYPE<>6
                                          ------------以上是本期合计   不包括调拨单的部分
             		  if (@SUMBAMOUNT is null) 
		     set  @SUMBAMOUNT=0
		  if (@SUMBQTY is null)   
			set @SUMBQTY=0
		  if (@SUMBPRICE is null)   
			set @SUMBPRICE=0
		  if (@INAMOUNTSUM is null)   
			set @INAMOUNTSUM=0
		  if (@INQTYSUM is null)   
			set @INQTYSUM=0

                         SET      @INAMOUNTSUM = @SUMBAMOUNT+@INAMOUNTSUM
                         SET      @INQTYSUM = @SUMBQTY+@INQTYSUM
		  if (-0.0000001<@INQTYSUM and @INQTYSUM<0.0000001)
		  begin
		   set   @INQTYSUM=0
		  end 
                             SET      @SUMBPRICE=ROUND(@INAMOUNTSUM/  @INQTYSUM,10)

	          UPDATE   DETAILBILLFLOW  set    INPRICE= @SUMBPRICE
                         where (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=1   )  AND ( INOUTFLAG = -1  OR  BILLTYPE = 5   OR   BILLTYPE = 6  OR  BILLTYPE = 12)
        END     ----------- IF    @INF_COSTINGTYPEID=3       END    全月平均一次计算价格   特别处理盘点和调拨
----------------------------------------------------------------
        IF   ( @INF_COSTINGTYPEID=1) OR   ( @INF_COSTINGTYPEID=3)  OR ( @INF_COSTINGTYPEID=2)  ----------- IF    @INF_COSTINGTYPEID=1 和 ( @INF_COSTINGTYPEID=3)      BEGIN     移动加权方式
        BEGIN
	       ---------注意是分仓库核算成本价格，每个仓库数量都是不同的！
                    ---------移动加权、全月一次平均以及个别指定算法都是一样的（基本一样，不同之处以上部分就是）
	    declare APRICE_TEMP Cursor READ_ONLY for Select ID, GOODSID ,
             		     isnull(INQTY,0) as INqty,isnull(INPRICE,0) as INPRICE ,
             		     isnull(EQTY,0) as EQTY , isnull(EPRICE,0) as EPRICE , INOUTFLAG, isnull(EAMOUNT,0) as EAMOUNT ,BILLTYPE,
			 isnull(MINQTY,0) as MINqty,  isnull(MEQTY,0) as MEqty
	                  from DetailBillFlow   where (rtrim(YYYYMM) >= @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=1   )
             		      ORDER BY BILLDATE,ID

	    Open APRICE_TEMP

	    fetch APRICE_TEMP into @ID,@GOODSID,@INqty,@INPRICE,@Eqty,@EPRICE,@INOUTFLAG,@EAMOUNT, @BILLTYPE,@MINQTY,@MEQTY


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	         IF (@INOUTFLAG=1)   and (@BILLTYPE<>5)  and  (@BILLTYPE<>6)  AND  (@BILLTYPE<>12)
	         BEGIN
	          Select @NEWEqty=NEWQTY,@MNEWEqty=MNEWQTY,@NEWEPRICE=NEWPRICE,@NEWEAMOUNT=NEWAMOUNT
             		       from  APRICECACULATOR    (@SUMBQTY,@MSUMBQTY,@SUMBPRICE,@SUMBAMOUNT,@INqty,@MINqty,@INPRICE,@INOUTFLAG)
	             ---定义的函数APRICECACULATOR
	          UPDATE   DETAILBILLFLOW  set    EQTY=@NEWEQTY, MEQTY=@MNEWEQTY,EPRICE=@NEWEPRICE,EAMOUNT=@NEWEAMOUNT
             		           WHERE ID=@ID
	         END
	         IF ( @INOUTFLAG = -1   )              OR  (@INOUTFLAG = 1  AND @BILLTYPE=5)    OR  (@INOUTFLAG = 1  AND @BILLTYPE = 6)    OR  (@INOUTFLAG = 1  AND @BILLTYPE =12)  
	         BEGIN
	                       if  (@INF_COSTINGTYPEID=1)
                                    BEGIN 
			          Select @NEWEqty=NEWQTY,@MNEWEqty=MNEWQTY,@NEWEPRICE=NEWPRICE,@NEWEAMOUNT=NEWAMOUNT
			       from  APRICECACULATOR    (@SUMBQTY,@MSUMBQTY,@SUMBPRICE,@SUMBAMOUNT,@INqty,@MINqty,@SUMBPRICE,@INOUTFLAG)
	             ---定义的函数APRICECACULATOR
		          UPDATE   DETAILBILLFLOW  set    EQTY=@NEWEQTY,EPRICE=@NEWEPRICE,EAMOUNT=@NEWEAMOUNT,INPRICE=@SUMBPRICE
             			           WHERE ID=@ID
                                    END
	                       if  @INF_COSTINGTYPEID=3 
                                    BEGIN 
			          Select @NEWEqty=NEWQTY,@MNEWEqty=MNEWQTY,@NEWEPRICE=NEWPRICE,@NEWEAMOUNT=NEWAMOUNT
             			       from  APRICECACULATOR    (@SUMBQTY,@MSUMBQTY,@SUMBPRICE,@SUMBAMOUNT,@INqty,@MINqty,@INPRICE,@INOUTFLAG)
		          UPDATE   DETAILBILLFLOW  set    EQTY=@NEWEQTY,EPRICE=@NEWEPRICE,EAMOUNT=@NEWEAMOUNT
             			           WHERE ID=@ID
                                    END
	         END
		----------------begin
             		------此期间可以写反填出库单据的单价
                          ------以后在此写DETAILBILLFLOW中的INQTY和INPRICE相当于反填单据
                          -----只对出库单据操作，因为单据的成本价采用计算字段
		----------------end
	        set    @SUMBQTY=@NEWEqty
	        set    @MSUMBQTY=@MNEWEqty
	        set    @SUMBPRICE=@NEWEPRICE
	        set    @SUMBAMOUNT=@NEWEAMOUNT

	    fetch APRICE_TEMP into @ID,@GOODSID,@INqty,@INPRICE,@Eqty,@EPRICE,@INOUTFLAG,@EAMOUNT, @BILLTYPE,@MINQTY,@MEQTY
 
--	            update   GOODS   SET APRICE = @NEWEPRICE WHERE  GOODSID=@GOODSID

	    END           ------- APRICE_TEMP  WHILE

	    close APRICE_TEMP
	    deallocate APRICE_TEMP

        END              -------------------        IF    @INF_COSTINGTYPEID=1    和 ( @INF_COSTINGTYPEID=3)     END
-----------------------------------------------------------------------------------------------------------------------------------------------------------


END







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG






































--------------------------------------------------------------------
--Create by li fa zheng  2012/09/01              
--功能： 本会计期间核算先进先出成本
--
--
--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[APRICECACULATOR_YYYYMM_XIAN ]  (@GOODSID  varchar(30),@STOREID00  varchar(30),
@YYYYMM  varchar(6)    )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 
declare @INOUTFLAG NUMERIC(20,6)
declare @BQTY NUMERIC(20,6)
declare @BPRICE NUMERIC(20,6)
declare @INQTY NUMERIC(20,6)
declare @INQTYSUM NUMERIC(20,6)
declare @INAMOUNTSUM  NUMERIC(20,6)
declare @INPRICE NUMERIC(20,6)
declare @EQTY NUMERIC(20,6)
declare @EPRICE NUMERIC(20,6)
declare @EAMOUNT NUMERIC(20,6)

declare @NEWEQTY NUMERIC(20,6)
declare @NEWEPRICE NUMERIC(20,6)
declare @NEWEAMOUNT NUMERIC(20,6)
declare @OUTAMOUNT NUMERIC(20,6)

declare @SUMBAMOUNT NUMERIC(20,6)            ---本期期初总金额
declare @SUMBQTY NUMERIC(20,6)                    ---本期期初总数量
declare @MSUMBQTY NUMERIC(20,6)                    ---本期期初总数量
declare @OUTQTY NUMERIC(20,6)                    ---本期期初总数量
declare @OUTMQTY NUMERIC(20,6)                    ---本期期初总数量
declare @KeYongQTY NUMERIC(20,6)                    ---本期期初总数量
declare @KeYongMQTY NUMERIC(20,6)                    ---本期期初总数量
declare @KeYongAMOUNT NUMERIC(20,6)                    ---本期期初总数量
declare @KeYongPrice NUMERIC(20,6)                    ---本期期初总数量
declare @TMPKeYongQTY NUMERIC(20,6)                    ---本期期初总数量
declare @TMPKeYongMQTY NUMERIC(20,6)                    ---本期期初总数量
declare @TMPKeYongAMOUNT NUMERIC(20,6)                    ---本期期初总数量
declare @TMPKeYongPrice NUMERIC(20,6)                    ---本期期初总数量
declare @TMPQTY NUMERIC(20,6)                    ---本期期初总数量
declare @TMPMQTY NUMERIC(20,6)                    ---本期期初总数量
declare @MINQTY NUMERIC(20,10)
declare @MEQTY NUMERIC(20,10)
declare @MNEWEQTY NUMERIC(20,10)


declare @SUMBPRICE NUMERIC(20,6)                 ---本期期初加权价

declare @INF_COSTINGTYPEID  INT                ---本期期初加权价

declare @ITEMNO varchar(15)               --明细存货编号
declare @MINbilldate  datetime   
declare @Billdate  datetime   


declare @BILLID varchar(22)           --单号
declare @StoreID varchar(22)           --单号

declare @BILLTYPE INT

declare @ID varchar(50)           --单号
declare @KeYongID varchar(50)           --单号

 
BEGIN

------------------------------------------------------------------------------------
          SELECT   @SUMBAMOUNT=(SELECT    isnull(SUM(BAMOUNT),0)  FROM  DetailBillFlow     where    (rtrim(GOODSID) = @GOODSID)    and (rtrim(YYYYMM) = @YYYYMM)      AND  YYYYMMBILL=0    )
          SELECT   @SUMBQTY=(SELECT    isnull(SUM(BQTY),0)   FROM  DetailBillFlow     where    (rtrim(GOODSID) = @GOODSID)    and (rtrim(YYYYMM) = @YYYYMM)     AND  YYYYMMBILL=0   )
          SELECT   @MSUMBQTY=(SELECT    isnull(SUM(MBQTY),0)   FROM  DetailBillFlow     where    (rtrim(GOODSID) = @GOODSID)    and (rtrim(YYYYMM) = @YYYYMM)     AND  YYYYMMBILL=0   )


                          IF    @SUMBQTY<>0
                          BEGIN
		SELECT   @SUMBPRICE=@SUMBAMOUNT/@SUMBQTY
		END
                           ELSE
                          BEGIN
		SELECT   @SUMBPRICE=0
		END
                                       -------以上是期初数据

       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID

        IF   @INF_COSTINGTYPEID=6   ----------- IF    @INF_COSTINGTYPEID=1 和 ( @INF_COSTINGTYPEID=3)      BEGIN     移动加权方式
        BEGIN
	       ---------注意是分仓库核算成本价格，每个仓库数量都是不同的！
                    ---------移动加权、全月一次平均以及个别指定算法都是一样的（基本一样，不同之处以上部分就是）

		---算法设计，先核算出库单价

------------------恢复本会计期间的可用数量

/*		update DetailBillFlow set EQTY=StoreEqty,Eprice=STOREEPrice,EAMOUNT=StoreEAMOUNT
				 where (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2   )
						 AND INOUTFLAG = 1   
						 AND  (rtrim(STOREID) = @STOREID00) 

*/

		update DetailBillFlow set EQTY=INQTY,MEQTY=MINQTY,Eprice=INPRICE,EAMOUNT=INQTY*INPRICE
				 where (rtrim(YYYYMM) >= @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2   )
						 AND INOUTFLAG = 1   


	    declare APRICE_TEMP Cursor READ_ONLY for Select ID, GOODSID ,StoreID,
             		     isnull(INQTY,0) as INqty,isnull(INPRICE,0) as INPRICE ,
             		     isnull(EQTY,0) as EQTY , isnull(EPRICE,0) as EPRICE , INOUTFLAG, isnull(EAMOUNT,0) as EAMOUNT ,
				BILLTYPE,BILLID,BILLDATE,
			 isnull(MINQTY,0) as MINqty,  isnull(MEQTY,0) as MEqty

	                  from DetailBillFlow   where (rtrim(YYYYMM) >= @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=1   )
             		      ORDER BY BILLDATE,ID

	    Open APRICE_TEMP

	    fetch APRICE_TEMP into @ID,@GOODSID,@StoreID,@INqty,@INPRICE,@Eqty,@EPRICE,@INOUTFLAG,@EAMOUNT, @BILLTYPE,@BILLID,@Billdate,@MINQTY,@MEQTY


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	         IF (@INOUTFLAG=1)    AND  (@BILLTYPE<>216)
	         BEGIN

			IF   @BILLTYPE=6
			BEGIN
				Select @INPRICE=@SUMBPRICE
			END
			 
		          Select @NEWEqty=NEWQTY,@MNEWEqty=MNEWQTY,@NEWEPRICE=NEWPRICE,@NEWEAMOUNT=NEWAMOUNT
             		       from  APRICECACULATOR    (@SUMBQTY,@MSUMBQTY,@SUMBPRICE,@SUMBAMOUNT,@INqty,@MINqty,@INPRICE,@INOUTFLAG)
	             ---定义的函数APRICECACULATOR
		          UPDATE   DETAILBILLFLOW  set    EQTY=@NEWEQTY, MEQTY=@MNEWEQTY,EPRICE=@NEWEPRICE,EAMOUNT=@NEWEAMOUNT
             		           WHERE ID=@ID

			IF   @BILLTYPE=6
			BEGIN
		          UPDATE   DETAILBILLFLOW  set   INPRICE=@INPRICE
             		           WHERE ID=@ID

		          UPDATE   DETAILBILLFLOW  set   INPRICE=@INPRICE,EPRICE=@INPRICE,EAMOUNT=INQTY*@INPRICE
					where (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2   )
						  AND BILLTYPE=6 AND BILLID=@BILLID
			END

--			print @NEWEQTY
	         END
	         IF ( @INOUTFLAG = -1   )  OR  (@INOUTFLAG = 1  AND @BILLTYPE=7)  
	         BEGIN

		         IF    (@BILLTYPE<>216)   
		         BEGIN

			----在这里先计算出库单价
			----	逐行提取
				set @OUTQTY=@INqty
				set @OUTMQTY=@MINqty
				set @KeYongQTY=0
				set @KeYongMQTY=0
				set @KeYongPrice=0
				set @KeYongAMOUNT=0

				if @BILLTYPE =7         -----处理采购退货单
				begin
				set @OUTQTY=-@INqty
				set @OUTMQTY=-@MINqty
				end
			

				while @OUTQTY>0
				begin
					

				print @OUTQTY

					select  @MINBILLDATE=MIN(BILLDATE) from DETAILBILLFLOW where Eqty > 0 and 
					  (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2 )

					select @KeYongID=min(ID) from DETAILBILLFLOW where Eqty > 0 and 
					  (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2 )
								  AND  BILLDATE=@MinBILLDATE  
------假设存在的情况下
					select @TMPKeYongQTY=Eqty,@TMPKeYongMQTY=MEqty,@TMPKeyongPrice=Eprice,@TMPKeYongAMOUNT=EQTY*EPrice from DETAILBILLFLOW where ID=@KeYongID
					print @TMPKeYongQTY

					set @TMPQTY=@TMPKeYongQTY-@OUTQTY
					set @TMPMQTY=@TMPKeYongMQTY-@OUTMQTY
					if @TMPQTY<=0
					begin
					set @KeYongAMOUNT=@KeYongAMOUNT+@TMPKeYongAMOUNT
					update DETAILBILLFLOW set EQTY=0,MEQTY=0,EAMOUNT=0 where ID=@KeYongID
					set @OUTQTY=@OUTQTY-@TMPKeYongQTY
					set @OUTMQTY=@OUTMQTY-@TMPKeYongMQTY

					end
					else
					begin
					set @KeYongAMOUNT=@KeYongAMOUNT+@OUTQTY*@TMPKeyongPrice
					update DETAILBILLFLOW set EQTY=EQTY-@OUTQTY,MEQTY=MEQTY-@OUTMQTY where ID=@KeYongID
				print @KeYongID

					set @OUTQTY=@OUTQTY-@TMPKeYongQTY
					set @OUTMQTY=@OUTMQTY-@TMPKeYongMQTY
					end

				end     
			    
				set @KeYongPrice=(@KeYongAMOUNT/@INqty)

				if @BILLTYPE =7         -----处理采购退货单
				begin
				set @KeYongPrice=-(@KeYongAMOUNT/@INqty)
				end
			

				print @KeYongPrice
				
		          UPDATE   DETAILBILLFLOW  set    INPRICE=@KeYongPrice  WHERE ID=@ID

		          Select @NEWEqty=NEWQTY,@MNEWEqty=MNEWQTY,@NEWEPRICE=NEWPRICE,@NEWEAMOUNT=NEWAMOUNT
             			       from  APRICECACULATOR    (@SUMBQTY,@MSUMBQTY,@SUMBPRICE,@SUMBAMOUNT,@INqty,@MINqty,@KeYongPrice ,@INOUTFLAG)
		          UPDATE   DETAILBILLFLOW  set    EQTY=@NEWEQTY,MEQTY=@MNEWEQTY,EPRICE=@NEWEPRICE,EAMOUNT=@NEWEAMOUNT
             			          WHERE ID=@ID
		         END
	         END

-----------------------------------------------------
	         IF ( @INOUTFLAG = -1) AND (@BILLTYPE in (12,216)) 
	         BEGIN

--------------------------负数的处理

			----在这里先计算出库单价
			----	逐行提取
				set @OUTQTY=@INqty
				set @OUTMQTY=@MINqty
				set @KeYongQTY=0
				set @KeYongMQTY=0
				set @KeYongPrice=0
				set @KeYongAMOUNT=0

				set @OUTQTY=-@INqty
				set @OUTMQTY=-@MINqty
			

				while @OUTQTY>0
				begin
					

				print @OUTQTY
--------------------------------------销售退货、与退料单寻单价入库

					select  @MINBILLDATE=MIN(BILLDATE) from DETAILBILLFLOW where Eqty > 0 
						and INQTY>Eqty  AND
					  (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2 )

					select @KeYongID=MIN(ID) from DETAILBILLFLOW where Eqty > 0 
						and INQTY>Eqty AND
					  (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2 )
								 AND  BILLDATE=@MinBILLDATE  
------假设存在的情况下
					select @TMPKeYongQTY=INQTY-Eqty,@TMPKeYongMQTY=MINQTY-MEqty,@TMPKeyongPrice=Eprice,@TMPKeYongAMOUNT=(INQTY-Eqty)*EPrice from DETAILBILLFLOW where ID=@KeYongID
					print @TMPKeYongQTY

					set @TMPQTY=@OUTQTY-@TMPKeYongQTY
					set @TMPMQTY=@OUTMQTY-@TMPKeYongMQTY
					if @TMPQTY>=0
					begin
					set @KeYongAMOUNT=@KeYongAMOUNT+@TMPKeYongQTY*@TMPKeyongPrice
					update DETAILBILLFLOW set EQTY=INQTY,MEQTY=MINQTY where ID=@KeYongID
					set @OUTQTY=@OUTQTY-@TMPKeYongQTY
					set @OUTMQTY=@OUTMQTY-@TMPKeYongMQTY
					end
					else
					begin
				print @KeYongID
					set @KeYongAMOUNT=@KeYongAMOUNT+@OUTQTY*@TMPKeyongPrice
					update DETAILBILLFLOW set EQTY=EQTY+@OUTQTY,MEQTY=MEQTY+@OUTMQTY where ID=@KeYongID
					set @OUTQTY=@OUTQTY-@TMPKeYongQTY
					set @OUTMQTY=@OUTMQTY-@TMPKeYongMQTY


					end

				end     
			    
----				set @KeYongPrice=(@KeYongAMOUNT/@INqty)

				set @KeYongPrice=-(@KeYongAMOUNT/@INqty)
			

				
		          UPDATE   DETAILBILLFLOW  set    INPRICE=@KeYongPrice  WHERE ID=@ID

		          Select @NEWEqty=NEWQTY,@MNEWEqty=MNEWQTY,@NEWEPRICE=NEWPRICE,@NEWEAMOUNT=NEWAMOUNT
             			       from  APRICECACULATOR    (@SUMBQTY,@MSUMBQTY,@SUMBPRICE,@SUMBAMOUNT,@INqty,@MINqty,@KeYongPrice ,@INOUTFLAG)
		          UPDATE   DETAILBILLFLOW  set    EQTY=@NEWEQTY,MEQTY=@MNEWEQTY,EPRICE=@NEWEPRICE,EAMOUNT=@NEWEAMOUNT
             			          WHERE ID=@ID

	         END
--------------------------------------------------------------------

	        set    @SUMBQTY=@NEWEqty
	        set    @MSUMBQTY=@MNEWEqty
	        set    @SUMBPRICE=@NEWEPRICE
	        set    @SUMBAMOUNT=@NEWEAMOUNT

	    fetch APRICE_TEMP into @ID,@GOODSID,@StoreID,@INqty,@INPRICE,@Eqty,@EPRICE,@INOUTFLAG,@EAMOUNT, @BILLTYPE,@BILLID,@Billdate,@MINQTY,@MEQTY
 
	            update   GOODS   SET APRICE = @NEWEPRICE WHERE  GOODSID=@GOODSID

	    END           ------- APRICE_TEMP  WHILE

	    close APRICE_TEMP
	    deallocate APRICE_TEMP

-----------------////
		update DetailBillFlow set EAMOUNT=EQTY*INPRICE
				 where (rtrim(YYYYMM) >= @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2   )
						 AND INOUTFLAG = 1   




        END              -------------------        IF    @INF_COSTINGTYPEID=1    和 ( @INF_COSTINGTYPEID=3)     END
-----------------------------------------------------------------------------------------------------------------------------------------------------------


END



















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG
















--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE BANKINOUTMXBREP(@BANKID varchar(8) ,                        -----如果为0000则全部仓库
                                                                                            @Begin_Date   varchar(10) ,
                                                                                           @End_date   varchar(10) 
                        
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @end_dateAddone  datetime,
        @MAXBILLDATE  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8),
        @WHERESTING   varchar(1800)

declare @BANKNAME  varchar(50)
declare @BANKSTR  varchar(50)

declare @ID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare  @BILLTYPE  INTEGER
declare  @INOUTFLAG  INTEGER
declare @BILLCODE  nvarchar(50)
declare @BILLDATE  datetime
declare @BILLTYPENAME  nvarchar(50)
declare @INAMOUNT NUMERIC(20,10)
declare @OUTAMOUNT NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @EAMOUNTPREV NUMERIC(20,10)
---//==========
declare @BAMOUNT NUMERIC(20,10)
declare @MAXID  nvarchar(50)

                   set @now_date=(select   max(billDATE)   FROM BANKbillflow)

                          IF @now_date IS NULL
		BEGIN
			set @now_date='2029-10-12'         ----以后纠正此特殊值，此值为调试程序用
		END
                       

                          SELECT    @WHERESTING  = '  AND     BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+ @End_date+char(39) 
                          SELECT    @BANKSTR  = '  AND     BANKID ='+char(39)+@BANKID+char(39)


     

Create Table #temptable10
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL 
		)

Create Table #temptable1
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
    INOUTFLAG  INTEGER
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   ID , BILLID,BILLTYPE,BILLCODE,BILLDATE,BILLTYPE,  '
           SELECT  @SQLSTR = @SQLSTR+'INAMOUNT,OUTAMOUNT,EAMOUNT ,INOUTFLAG '
           SELECT  @SQLSTR = @SQLSTR+'  from BANKbillflow   where yyyymmbill=1    '  + @WHERESTING+@BANKSTR 
           SELECT  @SQLSTR = @SQLSTR+'  order by id '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
    INOUTFLAG  INTEGER
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (Select  ID,BILLID,BILLTYPE, BILLCODE,BILLDATE,BILLTYPENAME,
                                                     isnull(INAMOUNT,0) as INAMOUNT ,  isnull(OUTAMOUNT,0) as OUTAMOUNT ,
                                                     isnull(EAMOUNT,0) as EAMOUNT   from  #temptable1        )
                 begin
	    declare INOUTMXBREP Cursor for Select  ID,BILLID,BILLTYPE , BILLCODE,BILLDATE,BILLTYPENAME,
                                                       isnull(INAMOUNT,0) as INAMOUNT ,   isnull(OUTAMOUNT,0) as OUTAMOUNT ,
                                                     isnull(EAMOUNT,0) as EAMOUNT ,INOUTFLAG  from  #temptable1         ORDER BY BILLDATE,ID
	    Open INOUTMXBREP

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INAMOUNT,@OUTAMOUNT,@EAMOUNT,@INOUTFLAG

                 SELECT  @BANKNAME= BANKNAME   FROM BANK  WHERE BANKID=@BANKID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME         )
                                           VALUES  (@COUNTID, @BANKNAME)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          select @MAXBILLDATE=MAX(BILLDATE) FROM BANKbillflow   WHERE  BANKID=@BANKID   AND     BILLDATE  < @begin_date    AND YYYYMMBILL=1
                           SELECT  @MAXID=MAX(ID)  FROM BANKbillflow  WHERE  BANKID=@BANKID     AND  BILLDATE=@MAXBILLDATE   AND YYYYMMBILL=1
                                         IF @MAXID IS NULL
 			BEGIN
			SET  @BAMOUNT=0
			END
                                        ELSE
			BEGIN
	                           SELECT @BAMOUNT=EAMOUNT   FROM   BANKbillflow  WHERE ID=@MAXID
			END
                                                              
                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID , '期初结存',@BAMOUNT)
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
                       SELECT  @BILLTYPENAME=NAME FROM  BILLNAME  WHERE @BILLTYPENAME=BILLTYPEID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF @INOUTFLAG=1 
		BEGIN
			SELECT @INAMOUNT=@INAMOUNT
			SELECT @OUTAMOUNT=0
		END
		IF @INOUTFLAG=-1 
		BEGIN
			SELECT @OUTAMOUNT=@INAMOUNT
			SELECT @INAMOUNT=0
		END

                          INSERT    INTO   #temptable2  (ID,BILLID,BILLTYPE, BILLCODE,BILLDATE,BILLTYPENAME,
                                                               INAMOUNT,OUTAMOUNT,EAMOUNT)
                                           VALUES  (@COUNTID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INAMOUNT,@OUTAMOUNT,@EAMOUNT)
 		    SET @EAMOUNTPREV=@EAMOUNT

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INAMOUNT,@OUTAMOUNT,@EAMOUNT,@INOUTFLAG
 

	    END           ------- INOUTMXBREP  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期末结存',@EAMOUNT)

	    close INOUTMXBREP
	    deallocate INOUTMXBREP
        end     ------------  if exists
---------------------------
---------解决当前仓库本期间未发生业务的货品
--                  delete    #temptable1
            ELSE
            BEGIN

                          select @MAXBILLDATE=MAX(BILLDATE) FROM BANKbillflow   WHERE  BANKID=@BANKID   AND     BILLDATE  < @begin_date    AND YYYYMMBILL=1
                           SELECT  @ID=MAX(ID)  FROM BANKbillflow  WHERE  BANKID=@BANKID     AND  BILLDATE=@MAXBILLDATE   AND YYYYMMBILL=1


	             	  SELECT    @ID=ID,@EAMOUNT=EAMOUNT    FROM  BANKbillflow  WHERE    ID = @ID   

                 SELECT @BANKNAME=BANKNAME   FROM BANK  WHERE BANKID=@BANKID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME         )
                                           VALUES  (@COUNTID,@BANKNAME)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                                                              
                          INSERT    INTO   #temptable2  (ID , BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期初结存',@EAMOUNT)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期末结存',@EAMOUNT)

---------------------------
	END




--------------------------

 SELECT *  FROM #temptable2         ORDER BY ID





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG















CREATE PROCEDURE BANKYYYYMMDD(  @Begin_Date   varchar(10) ,
                                                                                           @End_date   varchar(10) ,  
                                                                                           @YYYYMM  varchar(8)    --------为当前会计期间
                         
                                                      ) as

Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000)
                   set @now_date=(select   max(billDATE)   FROM BANKBILLFLOW )
                          IF @now_date IS NULL
		BEGIN
			set @now_date='2009-12-12'         ----以后纠正此特殊值，此值为调试程序用
		END

----------------------------------------------------
		SELECT @SQLSTR='	 select  I.BANKID,   I.bankNAME,       '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0) -(isnull(BN.INAMOUNT,0)- isnull(BN00.INAMOUNT,0)) as BAMOUNT, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(BE.INAMOUNT,0)  AS INAMOUNT   ,ISNULL(BE00.INAMOUNT,0)  AS OUTAMOUNT,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0) -(isnull(BN.INAMOUNT,0)- isnull(BN00.INAMOUNT,0))'
		SELECT @SQLSTR=@SQLSTR+'+ isnull(BE.INAMOUNT,0)-isnull(BE00.INAMOUNT,0) as EAMOUNT' --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from BANK  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select BANKID,sum(INAMOUNT*INOUTFLAG)  as INAMOUNT  '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from BANKBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)
		SELECT @SQLSTR=@SQLSTR+'group by BANKID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.BANKID = I.BANKID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select BANKID,sum(BAMOUNT) as BAMOUNT '
		SELECT @SQLSTR=@SQLSTR+' from BANKBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by BANKID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.BANKID = I.BANKID  '
------------------------以上部分是取当前库存
		SELECT @SQLSTR=@SQLSTR+'  left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select BANKID,sum(INAMOUNT) as INAMOUNT      '
		SELECT @SQLSTR=@SQLSTR+'  from BANKBILLFLOW           '
		SELECT @SQLSTR=@SQLSTR+'  where YYYYMMBILL = 1    and BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+ @Now_Date+char(39) +'  AND INOUTFLAG =1'   
		SELECT @SQLSTR=@SQLSTR+' group by BANKID'	
		SELECT @SQLSTR=@SQLSTR+' ) as BN on BN.BANKID = I.BANKID'  
		SELECT @SQLSTR=@SQLSTR+'  left outer join '
		SELECT @SQLSTR=@SQLSTR+'  (  '
		SELECT @SQLSTR=@SQLSTR+'select BANKID,sum(INAMOUNT) as INAMOUNT     '
		SELECT @SQLSTR=@SQLSTR+' from BANKBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+ @Now_Date +char(39) +' AND INOUTFLAG =-1 '  
		SELECT @SQLSTR=@SQLSTR+' group by BANKID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BN00 on BN00.BANKID = I.BANKID  '
------------------------以上部分为取begin_date到Now_Date的库存
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select BANKID,sum(INAMOUNT) as INAMOUNT   '
		SELECT @SQLSTR=@SQLSTR+' from BANKBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+@End_Date+char(39)+' AND INOUTFLAG =1 '  
		SELECT @SQLSTR=@SQLSTR+' group by BANKID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE on BE.BANKID = I.BANKID  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select BANKID,sum(INAMOUNT) as INAMOUNT   '
		SELECT @SQLSTR=@SQLSTR+' from BANKBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+@End_Date +char(39)+'AND INOUTFLAG =-1' 
		SELECT @SQLSTR=@SQLSTR+' group by BANKID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE00 on BE00.BANKID = I.BANKID  '
                          SELECT @SQLSTR=@SQLSTR+'   where     I. BANKID in (select BANKID from BANKBILLFLOW where YYYYMM>='+char(39)+@YYYYMM+char(39)+')'  
	             SELECT @SQLSTR=@SQLSTR+'          order by  I.BANKID                '    
------------------------------------------------------------------------
--		       print   @SQLSTR

		EXEC(@SQLSTR)







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














CREATE PROCEDURE [BANK_CACULATOR_YYYYMM ]  (
	@BANKID  varchar(30),
	@YYYYMM  varchar(6)    )
AS 
 
declare @INOUTFLAG NUMERIC(20,10)
declare @INAMOUNT  NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @SUMBAMOUNT NUMERIC(20,10)            ---本期期初总金额
 
BEGIN

            select    @SUMBAMOUNT=isnull(BAMOUNT,0)   FROM   BANKBILLFlow  where    (rtrim(BANKID) = @BANKID) 
						  and (rtrim(YYYYMM) = @YYYYMM) 	and   ( YYYYMMBILL=0   )  
                                       -------以上是期初数据
----------------------------------------------------------------
	    declare BANK_CACULATOR Cursor for Select  BANKID , isnull(INAMOUNT,0) as INAMOUNT, INOUTFLAG, isnull(EAMOUNT,0) as EAMOUNT 
	                  from BANKBILLFlow   where (rtrim(YYYYMM) >= @YYYYMM)  AND ( BANKID=@BANKID)   and   ( YYYYMMBILL=1   )  
             		      ORDER BY BILLDATE,ID

	    Open BANK_CACULATOR

	    fetch BANK_CACULATOR into @BANKID,@INAMOUNT,@INOUTFLAG,@EAMOUNT


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
		 select    @SUMBAMOUNT=@SUMBAMOUNT+@INAMOUNT*@INOUTFLAG

	         	 UPDATE   BANKBILLFLOW  set   EAMOUNT=@SUMBAMOUNT      WHERE CURRENT OF  BANK_CACULATOR

		    fetch BANK_CACULATOR into @BANKID,@INAMOUNT,@INOUTFLAG,@EAMOUNT
 
	    END           ------- BANK_CACULATOR  WHILE

	    close BANK_CACULATOR
	    deallocate BANK_CACULATOR

-----------------------------------------------------------------------------------------------------------------------------------------------------------


END








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG
















--------------------------------------------------------------------

CREATE PROCEDURE BETWEEN_CURR_YYYYMM  
                 (
                  @BILLDATE DATEtime,
                  @flagreturn int output,     ---返回记帐成功  -- 0 不在此会计期间  --1 在会计期间
                  @BillYYYYMMreturn VARCHAR(10) output     ---返回记帐成功  -- 0 不在此会计期间  --1 在会计期间
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     

declare @MINBILLDATE DATEtime
declare @MAXBILLDATE DATEtime
declare @PRODUCTDATE DATEtime
declare @B_ID INTEGER
declare @STOREHSFS   INTEGER

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

     select @flagreturn = 1     

   declare  @PREV_YYYYMM          varchar(6)  -- 上一个会计年月
   declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
	if substring(@YYYYMM,5,2) = '12'  --- 如果当前会计月等于最大的会计月，将需要转入下年的的第一个会计年月
	begin
	    set @Next_YYYYMM   = convert(varchar,convert(int,substring(@YYYYMM,1,4))+1) +'01'  
	end
	else
	begin
	    set @Next_YYYYMM   = substring(@YYYYMM,1,4) +substring('00',1,2-len(convert(varchar,convert(int,substring(@YYYYMM,5,2))+1)))+convert(varchar,convert(int,substring(@YYYYMM,5,2))+1)
	end

	if substring(@YYYYMM,5,2) = '01'  --- 如果当前会计月等于最大的会计月，将需要转入下年的的第一个会计年月
	begin
	    set @PREV_YYYYMM   = convert(varchar,convert(int,substring(@YYYYMM,1,4))-1) +'12'  
	end
	else
	begin
	    set @PREV_YYYYMM   = substring(@YYYYMM,1,4) +substring('00',1,2-len(convert(varchar,convert(int,substring(@YYYYMM,5,2))-1)))+convert(varchar,convert(int,substring(@YYYYMM,5,2))-1)
	end

	declare @YYYYMMFS INTEGER
	declare @YYYYMMFSDATE  INTEGER
	declare @Billday  INTEGER

	       SELECT    @YYYYMMFS =(SELECT  YYYYMMFS   FROM   ACCINFO    WHERE   GUID='0001' )    
                IF @YYYYMMFS=1
	  BEGIN
		     SET  @MINBillDate = CONVERT(DATEtime,@YYYYMM+'01')
		     SET  @MAXBillDate =CONVERT(DATEtime,@Next_YYYYMM+'01')
		     set @BillYYYYMMreturn=convert(varchar,DATEPART(year,@BillDate))+substring('00',1,2-len(convert(varchar,DATEPART(month,@BillDate))))+convert(varchar,DATEPART(month,@BillDate))
	  END
               ELSE
               BEGIN
	       SELECT    @YYYYMMFSDATE =(SELECT  YYYYMMFSDATE   FROM   ACCINFO    WHERE   GUID='0001' )    
       
	     SET  @MINBillDate =DATEADD(day, @YYYYMMFSDATE, CONVERT(DATEtime,@PREV_YYYYMM+'01'))
	     SET  @MAXBillDate =DATEADD(day, @YYYYMMFSDATE, CONVERT(DATEtime,@YYYYMM+'01'))
        	SELECT @Billday =DATEPART(day, @BillDate)
		if @Billday> @YYYYMMFSDATE  -----分界线
		begin
		     set @BillYYYYMMreturn=convert(varchar,DATEPART(year,DATEADD(month,1,@BillDate)))+substring('00',1,2-len(convert(varchar,DATEPART(month,DATEADD(month,1,@BillDate)))))+convert(varchar,DATEPART(month,DATEADD(month,1,@BillDate)))
		end
		else
		begin
		     set @BillYYYYMMreturn=convert(varchar,DATEPART(year,@BillDate))+substring('00',1,2-len(convert(varchar,DATEPART(month,@BillDate))))+convert(varchar,DATEPART(month,@BillDate))
		end



	 END

----      IF (@BillDate<@MINBillDate)  OR (@BillDate>=@MAXBillDate)
----可以记账当前会计期间以后的单据
      IF (@BillDate<@MINBillDate)  
      BEGIN
      set @flagreturn = 0
      RETURN
      END







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












--------------------------------------------------------------------
--Create by li fa zheng  2004/05/11            
--------------------------------------------------------------------

CREATE PROCEDURE [Bs_Update_AREATree] (@gt_no varchar(8))     --APSOFTENCRYPTION       WITH ENCRYPTION
AS

--declare local variables needed
declare @PLCODE varchar(8)
declare @PPrevno varchar(8)

declare @DIndirect_no varchar(8)
declare @DDirect_no varchar(8)
declare @DSelf_no varchar(8)

declare @CLCODE varchar(8)
declare @CPrevno varchar(8)
declare @CPrevPrevno varchar(8)

declare @temp_no varchar(8)


--find the insert or update record in AREA
select @PLCODE=(LCODE), @PPrevno=(Prevno)
from AREA
where LCODE=@gt_no

--delete the old record in the AREAtree 
while exists(select * from AREAtree where self_no=@PLCODE)
begin
  select @DIndirect_no=(Indirect_no), @DDirect_no=(Direct_no), @DSelf_no=(Self_no) from AREAtree where self_no=@PLCODE 
  delete from AREAtree where (Indirect_no=@DIndirect_no) and (Direct_no=@DDirect_no) and (Self_no=@DSelf_no)
end

--insert into AREAtree

insert into AREATree (indirect_no, direct_no, self_no) 
  values (@PLCODE, @PLCODE, @PLCODE)
set @temp_no=@PLCODE

if @PPrevno='0000'
begin
  insert into AREATree (indirect_no, direct_no, self_no) 
    values ('000000', '000000', @PLCODE)  
end
else
begin
  while exists(select * from AREA where (LCODE=@temp_no))
  begin
    select @CLCODE=(LCODE), @CPrevno=(Prevno) from AREA where (LCODE=@temp_no)

    insert into AREATree (indirect_no, direct_no, self_no) 
      values (@CPrevno, @PPrevno, @PLCODE)  

    set @temp_no=@CPrevNo 
  end
end
  






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












--------------------------------------------------------------------
--Create by li fa zheng  2004/05/11             
--------------------------------------------------------------------

CREATE PROCEDURE [Bs_Update_GoodsTypeTree] (@gt_no varchar(8))   --APSOFTENCRYPTION       WITH ENCRYPTION
AS

--declare local variables needed
declare @PLCODE varchar(8)
declare @PPrevno varchar(8)

declare @DIndirect_no varchar(8)
declare @DDirect_no varchar(8)
declare @DSelf_no varchar(8)

declare @CLCODE varchar(8)
declare @CPrevno varchar(8)
declare @CPrevPrevno varchar(8)

declare @temp_no varchar(8)


--find the insert or update record in goodstype
select @PLCODE=(LCODE), @PPrevno=(Prevno)
from GoodsType
where LCODE=@gt_no

--delete the old record in the goodstypetree 
while exists(select * from goodstypetree where self_no=@PLCODE)
begin
  select @DIndirect_no=(Indirect_no), @DDirect_no=(Direct_no), @DSelf_no=(Self_no) from goodstypetree where self_no=@PLCODE 
  delete from goodstypetree where (Indirect_no=@DIndirect_no) and (Direct_no=@DDirect_no) and (Self_no=@DSelf_no)
end

--insert into goodstypetree

insert into GoodsTypeTree (indirect_no, direct_no, self_no) 
  values (@PLCODE, @PLCODE, @PLCODE)
set @temp_no=@PLCODE

if @PPrevno='0000'
begin
  insert into GoodsTypeTree (indirect_no, direct_no, self_no) 
    values ('000000', '000000', @PLCODE)  
end
else
begin
  while exists(select * from goodstype where (LCODE=@temp_no))
  begin
    select @CLCODE=(LCODE), @CPrevno=(Prevno) from goodstype where (LCODE=@temp_no)

    insert into GoodsTypeTree (indirect_no, direct_no, self_no) 
      values (@CPrevno, @PPrevno, @PLCODE)  

    set @temp_no=@CPrevNo 
  end
end
  






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












--------------------------------------------------------------------
--Create by li fa zheng  2004/05/11            
--------------------------------------------------------------------

CREATE PROCEDURE [Bs_Update_INTYPETree] (@gt_no varchar(8))     --APSOFTENCRYPTION       WITH ENCRYPTION
AS

--declare local variables needed
declare @PLCODE varchar(8)
declare @PPrevno varchar(8)

declare @DIndirect_no varchar(8)
declare @DDirect_no varchar(8)
declare @DSelf_no varchar(8)

declare @CLCODE varchar(8)
declare @CPrevno varchar(8)
declare @CPrevPrevno varchar(8)

declare @temp_no varchar(8)


--find the insert or update record in INTYPE
select @PLCODE=(LCODE), @PPrevno=(Prevno)
from INTYPE
where LCODE=@gt_no

--delete the old record in the INTYPEtree 
while exists(select * from INTYPEtree where self_no=@PLCODE)
begin
  select @DIndirect_no=(Indirect_no), @DDirect_no=(Direct_no), @DSelf_no=(Self_no) from INTYPEtree where self_no=@PLCODE 
  delete from INTYPEtree where (Indirect_no=@DIndirect_no) and (Direct_no=@DDirect_no) and (Self_no=@DSelf_no)
end

--insert into INTYPEtree

insert into INTYPETree (indirect_no, direct_no, self_no) 
  values (@PLCODE, @PLCODE, @PLCODE)
set @temp_no=@PLCODE

if @PPrevno='0000'
begin
  insert into INTYPETree (indirect_no, direct_no, self_no) 
    values ('000000', '000000', @PLCODE)  
end
else
begin
  while exists(select * from INTYPE where (LCODE=@temp_no))
  begin
    select @CLCODE=(LCODE), @CPrevno=(Prevno) from INTYPE where (LCODE=@temp_no)

    insert into INTYPETree (indirect_no, direct_no, self_no) 
      values (@CPrevno, @PPrevno, @PLCODE)  

    set @temp_no=@CPrevNo 
  end
end
  






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












--------------------------------------------------------------------
--Create by li fa zheng  2004/05/11            
--------------------------------------------------------------------

CREATE PROCEDURE [Bs_Update_OUTTYPETree] (@gt_no varchar(8))     --APSOFTENCRYPTION       WITH ENCRYPTION
AS

--declare local variables needed
declare @PLCODE varchar(8)
declare @PPrevno varchar(8)

declare @DIndirect_no varchar(8)
declare @DDirect_no varchar(8)
declare @DSelf_no varchar(8)

declare @CLCODE varchar(8)
declare @CPrevno varchar(8)
declare @CPrevPrevno varchar(8)

declare @temp_no varchar(8)


--find the insert or update record in OUTTYPE
select @PLCODE=(LCODE), @PPrevno=(Prevno)
from OUTTYPE
where LCODE=@gt_no

--delete the old record in the OUTTYPEtree 
while exists(select * from OUTTYPEtree where self_no=@PLCODE)
begin
  select @DIndirect_no=(Indirect_no), @DDirect_no=(Direct_no), @DSelf_no=(Self_no) from OUTTYPEtree where self_no=@PLCODE 
  delete from OUTTYPEtree where (Indirect_no=@DIndirect_no) and (Direct_no=@DDirect_no) and (Self_no=@DSelf_no)
end

--insert into OUTTYPEtree

insert into OUTTYPETree (indirect_no, direct_no, self_no) 
  values (@PLCODE, @PLCODE, @PLCODE)
set @temp_no=@PLCODE

if @PPrevno='0000'
begin
  insert into OUTTYPETree (indirect_no, direct_no, self_no) 
    values ('000000', '000000', @PLCODE)  
end
else
begin
  while exists(select * from OUTTYPE where (LCODE=@temp_no))
  begin
    select @CLCODE=(LCODE), @CPrevno=(Prevno) from OUTTYPE where (LCODE=@temp_no)

    insert into OUTTYPETree (indirect_no, direct_no, self_no) 
      values (@CPrevno, @PPrevno, @PLCODE)  

    set @temp_no=@CPrevNo 
  end
end
  






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












CREATE PROCEDURE [dbo].[CGRKGoodsPrice_Update]   --APSOFTENCRYPTION       WITH ENCRYPTION
as
declare @CODE00   [varchar] (25)   
declare @SFLAG  INTEGER
declare @BILLTYPE   INTEGER
declare @NewBILLDATE DATEtime
declare @GOODSID  varchar(20)
declare @MAXITEMNO  varchar(20)
declare @MAXITEMNO_PREV  varchar(20)
declare @DEQTY NUMERIC(20,6)
declare @MEQTY NUMERIC(20,6)
declare @DEQTY_CURR NUMERIC(20,6)
declare @MEQTY_CURR NUMERIC(20,6)

begin
--------计算所有仓库的库存
     exec Store_Yue_JiSuan
--------插入临时表 

Create Table #TEMP1 
      (   GOODSID  varchar(10) ,
	[DEQTY] NUMERIC(20,6)  NULL ,
	[MEQTY] NUMERIC(20,6)  NULL ,
		)
		
     insert into  #TEMP1    
     Select GOODsID,EQTY as DEQTY,UNITQTY as MEQTY from Store_GoodsID_YUE where EQTY <>0  OR unitQTY <>0

     update  CGRKGoodsPrice  set  DEQTY =  0,MEQTY=0  where isnull(DEQTY,0)<>0 OR isnull(MEQTY,0)<>0
     
     declare CGRK_Cur Cursor READ_ONLY for Select  GOODSID ,ISNULL(DEQTY,0),ISNULL(MEQTY,0) from #TEMP1     ORDER BY GoodsID

	    Open CGRK_Cur

	    fetch CGRK_Cur into @GOODSID ,@DEQTY,@MEQTY 


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	                       
	          select  @MAXITEMNO=max(ITEMNO) from CGRKGoodsPrice where GOODSID=@GOODSID
	          while (@MAXITEMNO is not null) and (@DEQTY>0 OR @MEQTY>0)
	          begin
	                  Select @DEQTY_CURR=quantity,@MEQTY_CURR=unitqty from CGRKGoodsPrice where GOODSID=@GOODSID  and ITEMNO=@MAXITEMNO 
	                  Select @DEQTY=@DEQTY-@DEQTY_CURR   
	                  Select @MEQTY=@MEQTY-@MEQTY_CURR   
	                  Select @MAXITEMNO_PREV=@MAXITEMNO
	            IF  @DEQTY<>-9999999999
	            begin
	                  if  @DEQTY < 0 
                      BEGIN 
 		                   UPDATE   CGRKGoodsPrice    set    DEQTY=@DEQTY+@DEQTY_CURR where GOODSID=@GOODSID  and ITEMNO=@MAXITEMNO              			         
 		                   select @DEQTY=-9999999999   -----小于0就不计算了
                      END
                      ELSE
                      BEGIN 
 		                   UPDATE   CGRKGoodsPrice    set    DEQTY=quantity where GOODSID=@GOODSID  and ITEMNO=@MAXITEMNO              			         
                      END
                end
	            IF  @DEQTY<>-9999999999
	            begin                     
	                  if  @MEQTY < 0 
                      BEGIN 
 		                   UPDATE   CGRKGoodsPrice    set    MEQTY=@MEQTY+@MEQTY_CURR where GOODSID=@GOODSID  and ITEMNO=@MAXITEMNO              			         
 		                   select @MEQTY=-9999999999
                      END
                      ELSE
                      BEGIN 
 		                   UPDATE   CGRKGoodsPrice    set    MEQTY=unitqty where GOODSID=@GOODSID  and ITEMNO=@MAXITEMNO              			         
                      END
                      
	                 select  @MAXITEMNO=max(ITEMNO) from CGRKGoodsPrice where GOODSID=@GOODSID and ITEMNO < @MAXITEMNO_PREV
                end
              END    ----end---while (@MAXITEMNO is not null) and (@DEQTY>0 OR @MEQTY>0)

	    fetch CGRK_Cur into @GOODSID ,@DEQTY,@MEQTY 
 

	    END           ------- CGRK_Cur  WHILE

	    close CGRK_Cur
	    deallocate CGRK_Cur

-----------------------------------------------------------------------------------------------------------------------------------------------------------
drop table #TEMP1

     
     

end

----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE CLIENTINOUTMXBREP(@CLIENTID varchar(8) ,                        -----如果为0000则全部仓库
                                                                                            @Begin_Date   varchar(10) ,
                                                                                           @End_date   varchar(10) 
                        
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @end_dateAddone  datetime,
        @MAXBILLDATE  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8),
        @WHERESTING   varchar(1800)

declare @CLIENTNAME  varchar(50)
declare @CLIENTSTR  varchar(50)
declare @BumenID  varchar(50)

declare @ID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare  @BILLTYPE  INTEGER
declare  @INOUTFLAG  INTEGER
declare @BILLCODE  nvarchar(50)
declare @BILLDATE  datetime
declare @BILLTYPENAME  nvarchar(50)
declare @INAMOUNT NUMERIC(20,10)
declare @OUTAMOUNT NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @EAMOUNTPREV NUMERIC(20,10)
---//==========
declare @BAMOUNT NUMERIC(20,10)
declare @MAXID  nvarchar(50)

                   set @now_date=(select   max(billDATE)   FROM CLIENTbillflow)

                          IF @now_date IS NULL
		BEGIN
			set @now_date='2029-10-12'         ----以后纠正此特殊值，此值为调试程序用
		END
                       

                          SELECT    @WHERESTING  = '  AND     BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+ @End_date+char(39) 
                          SELECT    @CLIENTSTR  = '  AND     CLIENTID ='+char(39)+@CLIENTID+char(39)


     

Create Table #temptable10
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL 
		)

Create Table #temptable1
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
    INOUTFLAG  INTEGER
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   ID , BILLID,BILLTYPE,BILLCODE,BILLDATE,BILLTYPE,  '
           SELECT  @SQLSTR = @SQLSTR+'INAMOUNT,OUTAMOUNT,EAMOUNT ,INOUTFLAG '
           SELECT  @SQLSTR = @SQLSTR+'  from CLIENTbillflow   where yyyymmbill=1    '  + @WHERESTING+@CLIENTSTR 
           SELECT  @SQLSTR = @SQLSTR+'  order by id '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
    INOUTFLAG  INTEGER ,
   BuMenID  nvarchar(50)  NULL
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (Select  ID,BILLID,BILLTYPE, BILLCODE,BILLDATE,BILLTYPENAME,
                                                     isnull(INAMOUNT,0) as INAMOUNT ,  isnull(OUTAMOUNT,0) as OUTAMOUNT ,
                                                     isnull(EAMOUNT,0) as EAMOUNT   from  #temptable1        )
                 begin
	    declare INOUTMXBREP Cursor for Select  ID,BILLID,BILLTYPE , BILLCODE,BILLDATE,BILLTYPENAME,
                                                       isnull(INAMOUNT,0) as INAMOUNT ,   isnull(OUTAMOUNT,0) as OUTAMOUNT ,
                                                     isnull(EAMOUNT,0) as EAMOUNT ,INOUTFLAG  from  #temptable1         ORDER BY BILLDATE,ID
	    Open INOUTMXBREP

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INAMOUNT,@OUTAMOUNT,@EAMOUNT,@INOUTFLAG

                 SELECT  @CLIENTNAME=NAME   FROM CLIENT  WHERE CLIENTID=@CLIENTID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME         )
                                           VALUES  (@COUNTID, @CLIENTNAME)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                           select @MAXBILLDATE=MAX(BILLDATE) FROM CLIENTbillflow   WHERE  CLIENTID=@CLIENTID   AND     BILLDATE  < @begin_date     AND YYYYMMBILL=1
                           SELECT  @MAXID=MAX(ID)  FROM CLIENTbillflow  WHERE  CLIENTID=@CLIENTID     AND  BILLDATE=@MAXBILLDATE   AND YYYYMMBILL=1
                                         IF @MAXID IS NULL
 			BEGIN
			SET  @BAMOUNT=0
			END
                                        ELSE
			BEGIN
	                           SELECT @BAMOUNT=EAMOUNT   FROM   CLIENTbillflow  WHERE ID=@MAXID
			END
                                                              
                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID , '期初结存',@BAMOUNT)
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
                       SELECT  @BILLTYPENAME=NAME FROM  BILLNAME  WHERE @BILLTYPENAME=BILLTYPEID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF @INOUTFLAG=1 
		BEGIN
			SELECT @INAMOUNT=@INAMOUNT
			SELECT @OUTAMOUNT=0
		END
		IF @INOUTFLAG=-1 
		BEGIN
			SELECT @OUTAMOUNT=@INAMOUNT
			SELECT @INAMOUNT=0
		END

-----------------2012.08.01增加部门
                 select @bumenID=bumenID from ViewBILL where BILLID=@BillID AND BILLTYPE=@BILLTYPE

-----------------

                          INSERT    INTO   #temptable2  (ID,BILLID,BILLTYPE, BILLCODE,BILLDATE,BILLTYPENAME,
                                                               INAMOUNT,OUTAMOUNT,EAMOUNT,bumenID)
                                           VALUES  (@COUNTID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INAMOUNT,@OUTAMOUNT,@EAMOUNT,@bumenID)
 		    SET @EAMOUNTPREV=@EAMOUNT

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INAMOUNT,@OUTAMOUNT,@EAMOUNT,@INOUTFLAG
 

	    END           ------- INOUTMXBREP  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期末结存',@EAMOUNT)

	    close INOUTMXBREP
	    deallocate INOUTMXBREP
        end     ------------  if exists
---------------------------
---------解决当前仓库本期间未发生业务的货品
--                  delete    #temptable1
            ELSE
            BEGIN

                           select @MAXBILLDATE=MAX(BILLDATE) FROM CLIENTbillflow   WHERE  CLIENTID=@CLIENTID   AND     BILLDATE  < @begin_date     AND YYYYMMBILL=1
                           SELECT  @MAXID=MAX(ID)  FROM CLIENTbillflow  WHERE  CLIENTID=@CLIENTID     AND  BILLDATE=@MAXBILLDATE   AND YYYYMMBILL=1


	             	  SELECT    @ID=ID,@EAMOUNT=EAMOUNT    FROM  CLIENTbillflow  WHERE    ID = @MAXID

                 SELECT @CLIENTNAME=NAME   FROM CLIENT  WHERE CLIENTID=@CLIENTID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME         )
                                           VALUES  (@COUNTID,@CLIENTNAME)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                                                              
                          INSERT    INTO   #temptable2  (ID , BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期初结存',@EAMOUNT)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期末结存',@EAMOUNT)

---------------------------
	END




--------------------------

 SELECT *  FROM #temptable2         ORDER BY ID






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG
























--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE CLIENTXSCKMXB( @WHERESTING   varchar(1800)
                       
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8)

declare @GOODSNAME  varchar(50)
declare @CLIENTNAME  varchar(50)

declare @ID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @BILLTYPE  INT
declare @PRICETYPE  INT
declare @CaiZhi  varchar(50)
declare @SpecNameD  varchar(50)
declare @ChanDi  varchar(50)
declare @FuZhuQTY  varchar(50)
declare @CLIENTID  nvarchar(50)
declare @GOODSCODE  nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLCODE  nvarchar(50)
declare @BILLDATE  datetime
declare @BILLDATE00  datetime
declare @CLIENTID00  nvarchar(50)
declare @PRICE NUMERIC(20,10)
declare @QUANTITY NUMERIC(20,10)
declare @TAXRATE  NUMERIC(20,10)
declare @DISC  NUMERIC(20,10)
declare @UNITPRICE NUMERIC(20,10)
declare @UNITQTY NUMERIC(20,10)
declare @SUMAMT NUMERIC(20,10)
declare @SUMTAXAMT NUMERIC(20,10)
declare @SUMDayAMT NUMERIC(20,10)
declare @SUMDayTAXAMT NUMERIC(20,10)
declare @AMT NUMERIC(20,10)
declare @TAXAMT NUMERIC(20,10)
declare @ClientFlag smallint 
declare @ClientFlag00 smallint 
    

Create Table #temptable1
      (   CLIENTID varchar(50)  NULL,
       GOODSID  varchar(10) ,
       GOODScode  varchar(30) ,
      BILLID  nvarchar(50)  NULL,
      BILLTYPE INT,
	[PRICE] NUMERIC(20,10)  NULL ,
	[DISC] NUMERIC(20,10)  NULL ,
	[QUANTITY] NUMERIC(20,10)  NULL ,
	[TAXRATE]NUMERIC(20,10)  NULL ,
	BILLDATE DATEtime,
	[UNITPRICE] NUMERIC(20,10)  NULL ,
	[UNITQTY]NUMERIC(20,10)  NULL ,
		     PRICETYPE  INT ,
	[AMT]NUMERIC(20,10)  NULL ,
	[TAXAMT]NUMERIC(20,10)  NULL, 
	[ClientFlag]smallint  NULL ,
       ChanDi  varchar(30) ,
       FuZhuQTY  varchar(30) ,
       SpecNameD varchar(30) ,
       CaiZhi  varchar(30) 
	)

           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   CLIENTID,VIEWXSCK.GOODSID, GOODS.CODE AS GOODSCODE,BILLID,BILLTYPE,PRICE,DISC,QUANTITY,TAXRATE,BILLDATE '
           SELECT  @SQLSTR = @SQLSTR+'  ,UNITPRICE,UNITQTY,PRICETYPE,AMT,TAXAMT,ClientFlag,ChanDi,FuZhuQTY,SpecNameD,CaiZhi  from VIEWXSCK  ,GOODS  '  + @WHERESTING +'  AND  VIEWXSCK.GOODSID = GOODS.GOODSID'
           SELECT  @SQLSTR = @SQLSTR+'  order by CLIENTID,VIEWXSCK.GOODSID,BILLDATE,BILLID '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   GOODSNAME  nvarchar(50)  NULL,
   GOODSCODE  nvarchar(50)  NULL,
   UNIT  nvarchar(10)  NULL,
	[QUANTITY] NUMERIC(20,10)  NULL ,
	[PRICE] NUMERIC(20,10)  NULL ,
	[TAXRATE]NUMERIC(20,10)  NULL ,
	[AMT]NUMERIC(20,10)  NULL ,
	[TAXAMT]NUMERIC(20,10)  NULL, 
	  priceTYPENAME  nvarchar(10)  NULL,
       ChanDi  varchar(30) ,
       FuZhuQTY  varchar(30) ,
       SpecNameD varchar(30) ,
       CaiZhi  varchar(30) 
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (select  CLIENTID, GOODSID, BILLID,PRICE,DISC,QUANTITY,TAXRATE   from  #temptable1        )
                 begin
	    declare XSCKMXB_CLIENT Cursor for select  CLIENTID, GOODSID, BILLID,PRICE,DISC,QUANTITY,TAXRATE,BILLTYPE,DISC ,UNITPRICE,UNITQTY,PRICETYPE,AMT,TAXAMT,ClientFlag,ChanDi,FuZhuQTY,CaiZhi,SpecNameD,BILLDATE    from  #temptable1  
                                                            ORDER BY  CLIENTID,ClientFlag,BILLDATE,GOODSCODE, BILLID
	    Open XSCKMXB_CLIENT

	    fetch XSCKMXB_CLIENT into   @CLIENTID,@GOODSID,@BILLID,@PRICE,@DISC,@QUANTITY,@TAXRATE,@BILLTYPE,@DISC ,@UNITPRICE,@UNITQTY,@PRICETYPE,@AMT,@TAXAMT,@ClientFlag,@ChanDi,@FuZhuQTY,@CaiZhi,@SpecNameD,@BILLDATE

                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @CLIENTNAME =(SELECT NAME   FROM ViewCLIENT  WHERE CLIENTID=@CLIENTID  and CLIENTFlag=@CLIENTFlag)
                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)

                 SELECT  @CLIENTID00=@CLIENTID
		 SELECT  @CLIENTFlag00=@CLIENTFlag
                 SELECT  @BILLDATE00=@BILLDATE

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                                           VALUES  (@COUNTID,@CLIENTNAME)
		SELECT @SUMAMT=0
		SELECT @SUMTAXAMT=0
		SELECT @SUMDayAMT=0
		SELECT @SUMDayTAXAMT=0
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID



		IF  not( @BILLDATE00=@BILLDATE)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,AMT,TAXAMT)
                                           VALUES  (@COUNTID, '按日小计',@SUMDayAMT,@SUMDayTAXAMT)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

----		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
----			         SELECT  @CLIENTNAME =(SELECT NAME   FROM ViewCLIENT  WHERE CLIENTID=@CLIENTID  and CLIENTFlag=@CLIENTFlag)
----		                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @BILLDATE00=@BILLDATE


			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                           	                VALUES  (@COUNTID,@CLIENTNAME)
				SELECT @SUMDayAMT=0
				SELECT @SUMDayTAXAMT=0
		END	






		IF  not( @CLIENTID00 = @CLIENTID AND @CLIENTFlag00=@CLIENTFlag)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,AMT,TAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMAMT,@SUMTAXAMT)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
			         SELECT  @CLIENTNAME =(SELECT NAME   FROM ViewCLIENT  WHERE CLIENTID=@CLIENTID  and CLIENTFlag=@CLIENTFlag)
		                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @CLIENTID00=@CLIENTID
				 SELECT  @CLIENTFlag00=@CLIENTFlag


			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                           	                VALUES  (@COUNTID,@CLIENTNAME)
				SELECT @SUMAMT=0
				SELECT @SUMTAXAMT=0
				SELECT @SUMDayAMT=0
				SELECT @SUMDayTAXAMT=0
		END	
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
	  			SELECT @UNIT = (SELECT UNIT   FROM GOODS  WHERE GOODSID=@GOODSID)
			IF @BILLTYPE=2
			BEGIN
			   SELECT @BILLCODE=(SELECT CODE   FROM STOREXSCKM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STOREXSCKM  WHERE BILLID=@BILLID)
			END
			IF @BILLTYPE=12
			BEGIN
			   SELECT @BILLCODE=(SELECT CODE   FROM STOREXSTHM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STOREXSTHM  WHERE BILLID=@BILLID)
			END
		                 SELECT  @GOODSNAME=(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @GOODSCODE=(SELECT CODE   FROM GOODS  WHERE GOODSID=@GOODSID)

				IF @PRICETYPE=1 
				BEGIN
			                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,GOODSNAME,GOODSCODE,UNIT, QUANTITY,PRICE,TAXRATE, AMT,TAXAMT,PRICETYPENAME,ChanDi,FuZhuQTY,CaiZhi,SpecNameD)
             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@GOODSNAME,@GOODSCODE,@UNIT,@QUANTITY,@UNITPRICE,@TAXRATE,@AMT,@TAXAMT,'重量',@ChanDi,@FuZhuQTY,@CaiZhi,@SpecNameD)
				END
				IF @PRICETYPE=0
				BEGIN
			                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,GOODSNAME,GOODSCODE,UNIT, QUANTITY,PRICE,TAXRATE, AMT,TAXAMT,PRICETYPENAME,ChanDi,FuZhuQTY,CaiZhi,SpecNameD)
             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@GOODSNAME,@GOODSCODE,@UNIT,@UNITQTY,@UNITPRICE,@TAXRATE,@AMT,@TAXAMT,'数量',@ChanDi,@FuZhuQTY,@CaiZhi,@SpecNameD)
				END
				SELECT @SUMAMT=@SUMAMT+@AMT
				SELECT @SUMTAXAMT=@SUMTAXAMT+@TAXAMT
				SELECT @SUMDayAMT=@SUMDayAMT+@AMT
				SELECT @SUMDayTAXAMT=@SUMDayTAXAMT+@TAXAMT
		
	    fetch XSCKMXB_CLIENT into   @CLIENTID,@GOODSID,@BILLID,@PRICE,@DISC,@QUANTITY,@TAXRATE,@BILLTYPE,@DISC ,@UNITPRICE,@UNITQTY,@PRICETYPE,@AMT,@TAXAMT,@ClientFlag,@ChanDi,@FuZhuQTY,@CaiZhi,@SpecNameD,@BILLDATE
 
	    END           ------- XSCKMXB_CLIENT  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,AMT,TAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMAMT,@SUMTAXAMT)

	    close XSCKMXB_CLIENT
	    deallocate XSCKMXB_CLIENT
        end     ------------  if exists

 SELECT *  FROM #temptable2         ORDER BY ID













----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG






--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE [dbo].[CLIENTXSDDMXB]( @WHERESTING   varchar(1800)
                       
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8)

declare @GOODSNAME  varchar(50)
declare @CLIENTNAME  varchar(50)

declare @ID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @CLIENTID  nvarchar(50)
declare @GOODSCODE  nvarchar(50)
declare @SpecName  nvarchar(50)
declare @ModelName  nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLCODE  nvarchar(50)
declare @BILLTYPE INT
declare @BILLDATE  datetime
declare @CLIENTID00  nvarchar(50)
declare @PRICE NUMERIC(20, 6)
declare @TAXAMT NUMERIC(20, 2)
declare @WCunitQTY NUMERIC(20, 6)
declare @WCquantity NUMERIC(20, 6)
declare @zzunitQTY NUMERIC(20, 6)
declare @zzquantity NUMERIC(20, 6)
declare @WCTAXAMT NUMERIC(20, 6)
declare @TAXRATE  NUMERIC(20, 6)
declare @RATE  NUMERIC(20, 6)
declare @WEITAXAMT NUMERIC(20, 6)
declare @SUMWCTAXAMT NUMERIC(20, 6)
declare @SUMWEITAXAMT NUMERIC(20, 6)
declare @SUMTAXAMT NUMERIC(20, 6)
declare @UNITQTY NUMERIC(20, 6)
declare @quantity NUMERIC(20, 6)
declare @UNITPRICE NUMERIC(20, 6)
declare @DISC NUMERIC(20, 6)
declare    @PRICETYPE int

Create Table #temptable1
      (   CLIENTID varchar(50)  NULL,
       GOODSID  varchar(10) ,
       GOODSCODE  varchar(30) ,
      BILLID  nvarchar(50)  NULL,
      BILLTYPE  INT ,
	[PRICE] NUMERIC(20, 6)  NULL ,
	[UNITQTY] NUMERIC(20, 6)  NULL ,
	[quantity] NUMERIC(20, 6)  NULL ,
	[DISC] NUMERIC(20, 6)  NULL ,
	[TAXRATE]NUMERIC(20, 6)  NULL ,
	   BILLDATE  datetime  NULL,
	[UNITPRICE] NUMERIC(20, 6)  NULL ,
	[WCunitQTY]NUMERIC(20, 6)  NULL ,
	[WCquantity]NUMERIC(20, 6)  NULL ,
	[zzunitQTY]NUMERIC(20, 6)  NULL ,
	[zzquantity]NUMERIC(20, 6)  NULL ,
	[TAXAMT]NUMERIC(20, 2)  NULL, 
	[PRICETYPE]    int  NULL, 
	       DETAILBILLFLOWID  varchar(10) 
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   VIEWXSDD.CLIENTID,VIEWXSDD.GOODSID,GOODS.CODE AS GOODSCODE, BILLID,BILLTYPE,PRICE,UNITQTY,quantity,DISC,TAXRATE,BILLDATE '
           SELECT  @SQLSTR = @SQLSTR+' ,UNITPRICE,WCunitQTY,WCquantity,zzunitQTY,zzquantity,TAXAMT,PRICETYPE,DETAILBILLFLOWID  from VIEWXSDD   ,GOODS  '  + @WHERESTING +'  AND  VIEWXSDD.GOODSID = GOODS.GOODSID'
           SELECT  @SQLSTR = @SQLSTR+'  order by VIEWXSDD.CLIENTID,VIEWXSDD.GOODSID,BILLDATE,DETAILBILLFLOWID '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
	   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   GOODSNAME  nvarchar(50)  NULL,
   GOODSCODE  nvarchar(50)  NULL,
      SpecName  nvarchar(50)  NULL,
   ModelName  nvarchar(50)  NULL,
UNIT  nvarchar(10)  NULL,
	[UNITQTY] NUMERIC(20, 6)  NULL ,
	[quantity] NUMERIC(20, 6)  NULL ,
	[TAXAMT]NUMERIC(20, 2)  NULL, 
	[WCunitQTY] NUMERIC(20, 6)  NULL ,
	[WCquantity] NUMERIC(20, 6)  NULL ,
	[zzunitQTY] NUMERIC(20, 6)  NULL ,
	[zzquantity] NUMERIC(20, 6)  NULL ,
	[WCTAXAMT]NUMERIC(20, 6)  NULL ,
	[WEIunitQTY] NUMERIC(20, 6)  NULL ,
	[WEIquantity] NUMERIC(20, 6)  NULL ,
	[WEITAXAMT]NUMERIC(20, 6)  NULL 
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (select  CLIENTID, GOODSID, BILLID,PRICE,UNITQTY,TAXRATE,BILLTYPE   from  #temptable1        )
                 begin
	    declare XSDDMXB_CLIENT Cursor for select  CLIENTID, GOODSID, BILLID,PRICE,UNITQTY,quantity,TAXRATE,BILLTYPE ,DISC,UNITPRICE,WCunitQTY,WCquantity, zzunitQTY,zzquantity,TAXAMT,PRICETYPE  from  #temptable1  
---                                                            ORDER BY  CLIENTID,  BILLDATE,DETAILBILLFLOWID,GOODSCODE
                                                            ORDER BY  CLIENTID,  BILLDATE,BILLID,GOODSCODE
	    Open XSDDMXB_CLIENT

	    fetch XSDDMXB_CLIENT into   @CLIENTID,@GOODSID,@BILLID,@PRICE,@UNITQTY,@quantity,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@WCunitQTY,@WCquantity,@zzunitQTY,@zzquantity,@TAXAMT,@PRICETYPE

                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @CLIENTNAME =(SELECT NAME   FROM CLIENT  WHERE CLIENTID=@CLIENTID)
                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)

                 SELECT  @CLIENTID00=@CLIENTID

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                                           VALUES  (@COUNTID,@CLIENTNAME)
		SELECT @SUMWCTAXAMT=0
		SELECT @SUMTAXAMT=0
		SELECT @SUMWEITAXAMT=0
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF  not( @CLIENTID00 = @CLIENTID)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,WCTAXAMT,TAXAMT,WEITAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMWCTAXAMT,@SUMTAXAMT,@SUMWEITAXAMT)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @CLIENTNAME =(SELECT NAME   FROM CLIENT  WHERE CLIENTID=@CLIENTID)
		                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @CLIENTID00=@CLIENTID


			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                           	                VALUES  (@COUNTID,@CLIENTNAME)
				SELECT @SUMWCTAXAMT=0
				SELECT @SUMTAXAMT=0
				SELECT @SUMWEITAXAMT=0
		END	
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

				--SELECT @RATE =RATE  FROM GOODSUNIT  WHERE GOODSID=@GOODSID AND UNITID=@UNITID

	  			SELECT @UNIT = (SELECT UNIT   FROM GOODS  WHERE GOODSID=@GOODSID)
				
			   SELECT @BILLCODE=(SELECT CODE   FROM STOREXSDDM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STOREXSDDM  WHERE BILLID=@BILLID)
               SELECT  @GOODSCODE=CODE,@GOODSNAME=Name,@SpecName=SpecName,@ModelName=ModelName     FROM GOODS  WHERE GOODSID=@GOODSID
		               if @PRICETYPE=1
		               begin  
		                 SET @WEITAXAMT=Round(ISNULL(@DISC,100)*0.01*(ISNULL(@quantity,0)-ISNULL(@WCquantity,0)-ISNULL(@zzquantity,0))*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
		                 SET @WCTAXAMT=Round(ISNULL(@DISC,100)*0.01*ISNULL(@WCquantity,0)*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
					   end
					   else
					   begin
		                 SET @WEITAXAMT=Round(ISNULL(@DISC,100)*0.01*(ISNULL(@unitqty,0)-ISNULL(@WCunitqty,0)-ISNULL(@zzunitqty,0))*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
		                 SET @WCTAXAMT=Round(ISNULL(@DISC,100)*0.01*ISNULL(@WCunitqty,0)*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
					   end
		                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,GOODSNAME,GOODSCODE,SpecName,ModelName,UNIT, UNITQTY,quantity,TAXAMT,WCunitQTY,WCquantity,zzunitQTY,zzquantity,WCTAXAMT,WEIunitQTY,WEIquantity,WEITAXAMT)
             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@GOODSNAME,@GOODSCODE,@SpecName,@ModelName,@UNIT,@UNITQTY,@quantity,
					                     @TAXAMT,
					                     ISNULL(@WCunitQTY,0) ,
					                     ISNULL(@WCquantity,0) ,
					                     ISNULL(@zzunitQTY,0) ,
					                     ISNULL(@zzquantity,0) ,					@WCTAXAMT,
					                      @UNITQTY-ISNULL(@WCunitQTY,0) -ISNULL(@zzunitQTY,0),
					                      @quantity-ISNULL(@WCquantity,0) -ISNULL(@zzquantity,0),@WEITAXAMT	)

				SELECT @SUMTAXAMT=@SUMTAXAMT+@TAXAMT
				SELECT @SUMWCTAXAMT=@SUMWCTAXAMT+@WCTAXAMT
				SELECT @SUMWEITAXAMT=@SUMWEITAXAMT+@WEITAXAMT
		
	    fetch XSDDMXB_CLIENT into   @CLIENTID,@GOODSID,@BILLID,@PRICE,@UNITQTY,@quantity,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@WCunitQTY,@WCquantity,@zzunitQTY,@zzquantity,@TAXAMT,@PRICETYPE
 
	    END           ------- XSDDMXB_CLIENT  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,WCTAXAMT,TAXAMT,WEITAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMWCTAXAMT,@SUMTAXAMT,@SUMWEITAXAMT)

	    close XSDDMXB_CLIENT
	    deallocate XSDDMXB_CLIENT
        end     ------------  if exists

 SELECT *  FROM #temptable2         ORDER BY ID











----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG

















CREATE PROCEDURE CLIENTYYYYMMDD(  @Begin_Date   varchar(10) ,
                                                                                           @End_date   varchar(10) ,  
                                                                                           @YYYYMM  varchar(8),      --------为当前会计期间
						           @LCODE  varchar(10),             ---如果LCODE  为‘GGGG’表示不对类别进行查询
						           @CLIENTCODE  varchar(20),             ---如果CLIENTCODE  为‘GGGG’表示不对类别进行查询
						           @CLIENTNAME  varchar(20),             ---如果CLIENTNAME  为‘GGGG’表示不对类别进行查询
                                                           @ZEROFLAG   smallint      --------  0  代表 不作为过滤条件

                         
                                                      ) as

Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @WHERESTING   varchar(1800)
                   set @now_date=(select   max(billDATE)   FROM  CLIENTBILLFLOW)
                          IF @now_date IS NULL
		BEGIN
			set @now_date='2009-12-12'         ----以后纠正此特殊值，此值为调试程序用
		END

		if     NOT (@LCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = '  AND   I.CLIENTID IN ( select G.CLIENTID from AREAtree T, CLIENT G where T.indirect_no = '+CHAR(39)+@LCODE+CHAR(39)+ '  AND T.self_no=G.AREAID )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  ='     '
 		END
		if     NOT (@CLIENTCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.CLIENTID IN ( select  CLIENTID from CLIENT   where  CODE LIKE   '+CHAR(39)+'%'+@CLIENTCODE+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  =@WHERESTING+'     '
 		END
		if     NOT (@CLIENTNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.CLIENTID IN ( select  CLIENTID from CLIENT   where  NAME LIKE   '+CHAR(39)+'%'+@CLIENTNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END

--                       print   @WHERESTING
----------------------------------------------------
		SELECT @SQLSTR='	 select  I.CLIENTID,  I.CODE,  I.NAME,       '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0) -(isnull(BN.INAMOUNT,0)- isnull(BN00.INAMOUNT,0)) as BAMOUNT, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(BE.INAMOUNT,0)  AS INAMOUNT   ,ISNULL(BE00.INAMOUNT,0)  AS OUTAMOUNT,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0) -(isnull(BN.INAMOUNT,0)- isnull(BN00.INAMOUNT,0))'
		SELECT @SQLSTR=@SQLSTR+'+ isnull(BE.INAMOUNT,0)-isnull(BE00.INAMOUNT,0) as EAMOUNT' --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from CLIENT  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select CLIENTID,sum(INAMOUNT*INOUTFLAG)  as INAMOUNT  '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from CLIENTBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)
		SELECT @SQLSTR=@SQLSTR+'group by CLIENTID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.CLIENTID = I.CLIENTID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select CLIENTID,sum(BAMOUNT) as BAMOUNT '
		SELECT @SQLSTR=@SQLSTR+' from CLIENTBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by CLIENTID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.CLIENTID = I.CLIENTID  '
------------------------以上部分是取当前库存
		SELECT @SQLSTR=@SQLSTR+'  left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select CLIENTID,sum(INAMOUNT) as INAMOUNT      '
		SELECT @SQLSTR=@SQLSTR+'  from CLIENTBILLFLOW           '
		SELECT @SQLSTR=@SQLSTR+'  where YYYYMMBILL = 1    and BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+ @Now_Date+char(39) +'  AND INOUTFLAG =1'   
		SELECT @SQLSTR=@SQLSTR+' group by CLIENTID'	
		SELECT @SQLSTR=@SQLSTR+' ) as BN on BN.CLIENTID = I.CLIENTID'  
		SELECT @SQLSTR=@SQLSTR+'  left outer join '
		SELECT @SQLSTR=@SQLSTR+'  (  '
		SELECT @SQLSTR=@SQLSTR+'select CLIENTID,sum(INAMOUNT) as INAMOUNT     '
		SELECT @SQLSTR=@SQLSTR+' from CLIENTBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+ @Now_Date +char(39) +' AND INOUTFLAG =-1 '  
		SELECT @SQLSTR=@SQLSTR+' group by CLIENTID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BN00 on BN00.CLIENTID = I.CLIENTID  '
------------------------以上部分为取begin_date到Now_Date的库存
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select CLIENTID,sum(INAMOUNT) as INAMOUNT   '
		SELECT @SQLSTR=@SQLSTR+' from CLIENTBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+@End_Date+char(39)+' AND INOUTFLAG =1 '  
		SELECT @SQLSTR=@SQLSTR+' group by CLIENTID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE on BE.CLIENTID = I.CLIENTID  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select CLIENTID,sum(INAMOUNT) as INAMOUNT   '
		SELECT @SQLSTR=@SQLSTR+' from CLIENTBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+@End_Date +char(39)+'AND INOUTFLAG =-1' 
		SELECT @SQLSTR=@SQLSTR+' group by CLIENTID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE00 on BE00.CLIENTID = I.CLIENTID  '
                SELECT @SQLSTR=@SQLSTR+'  where     I. CLIENTID in (select CLIENTID from CLIENTBILLFLOW where YYYYMM >='+char(39)+@YYYYMM+char(39)+')'  + @WHERESTING 
	        SELECT @SQLSTR=@SQLSTR+'          order by  I.CLIENTID                '    
------------------------------------------------------------------------
--		       print   @SQLSTR


Create Table #temptable2012YS
      (CLIENTID  varchar(10) primary key,
	    CODE  varchar(100) ,
	    NAME  varchar(100) ,
	  BAMOUNT NUMERIC(20,10)  NULL, 
	  INAMOUNT NUMERIC(20,10)  NULL, 
	  OUTAMOUNT NUMERIC(20,10)  NULL, 
	   EAMOUNT NUMERIC(20,10)  NULL 
		)

		INSERT INTO  #temptable2012YS  EXEC(@SQLSTR)


		IF  @ZEROFLAG=0
		BEGIN
                     SELECT *  FROM  #temptable2012YS
		END
		IF  @ZEROFLAG=1
		BEGIN
                     SELECT *  FROM  #temptable2012YS  where EAMOUNT<>0
		END











----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG







CREATE PROCEDURE CLIENTYYYYMMDD_BJ(  @Begin_Date   varchar(10) ,
                                                                                           @End_date   varchar(10) ,  
                                                                                           @YYYYMM  varchar(8)      --------为当前会计期间
                         
                                                      ) as

Declare 
        @end_dateAddone  datetime,
        @LastSKDate  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @ClientID   varchar(20),
        @SQLSTR   varchar(8000),
        @WHERESTING   varchar(1800)
                   set @now_date=(select   max(billDATE)   FROM  CLIENTBILLFLOW)
                          IF @now_date IS NULL
		BEGIN
			set @now_date='2009-12-12'         ----以后纠正此特殊值，此值为调试程序用
		END

			SELECT    @WHERESTING  ='     '

--                       print   @WHERESTING
----------------------------------------------------

CREATE TABLE #CLIENTTMP (
	[CLIENTID] [varchar] (25) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[CODE] [varchar] (50)  NULL ,
	[NAME] [varchar] (100)  NULL ,
	[CREDIT] NUMERIC(20,10) NULL ,
	[QiXianDays] int NULL ,
	[LastSKDate] datetime NULL ,
	[EAMOUNT] NUMERIC(20,10) NULL 
) ON [PRIMARY]





----------------------------------------------------
		SELECT @SQLSTR='	 select  I.CLIENTID,  I.CODE,  I.NAME, I.CREDIT,I.QiXianDays,getdate() AS LastSKDate,    '
--		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0) -(isnull(BN.INAMOUNT,0)- isnull(BN00.INAMOUNT,0)) as BAMOUNT, '   --期初数量
--		SELECT @SQLSTR=@SQLSTR+'ISNULL(BE.INAMOUNT,0)  AS INAMOUNT   ,ISNULL(BE00.INAMOUNT,0)  AS OUTAMOUNT,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0) -(isnull(BN.INAMOUNT,0)- isnull(BN00.INAMOUNT,0))'
		SELECT @SQLSTR=@SQLSTR+'+ isnull(BE.INAMOUNT,0)-isnull(BE00.INAMOUNT,0) as EAMOUNT' --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from CLIENT  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select CLIENTID,sum(INAMOUNT*INOUTFLAG)  as INAMOUNT  '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from CLIENTBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)
		SELECT @SQLSTR=@SQLSTR+'group by CLIENTID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.CLIENTID = I.CLIENTID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select CLIENTID,sum(BAMOUNT) as BAMOUNT '
		SELECT @SQLSTR=@SQLSTR+' from CLIENTBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by CLIENTID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.CLIENTID = I.CLIENTID  '
------------------------以上部分是取当前库存
		SELECT @SQLSTR=@SQLSTR+'  left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select CLIENTID,sum(INAMOUNT) as INAMOUNT      '
		SELECT @SQLSTR=@SQLSTR+'  from CLIENTBILLFLOW           '
		SELECT @SQLSTR=@SQLSTR+'  where YYYYMMBILL = 1    and BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+ @Now_Date+char(39) +'  AND INOUTFLAG =1'   
		SELECT @SQLSTR=@SQLSTR+' group by CLIENTID'	
		SELECT @SQLSTR=@SQLSTR+' ) as BN on BN.CLIENTID = I.CLIENTID'  
		SELECT @SQLSTR=@SQLSTR+'  left outer join '
		SELECT @SQLSTR=@SQLSTR+'  (  '
		SELECT @SQLSTR=@SQLSTR+'select CLIENTID,sum(INAMOUNT) as INAMOUNT     '
		SELECT @SQLSTR=@SQLSTR+' from CLIENTBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+ @Now_Date +char(39) +' AND INOUTFLAG =-1 '  
		SELECT @SQLSTR=@SQLSTR+' group by CLIENTID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BN00 on BN00.CLIENTID = I.CLIENTID  '
------------------------以上部分为取begin_date到Now_Date的库存
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select CLIENTID,sum(INAMOUNT) as INAMOUNT   '
		SELECT @SQLSTR=@SQLSTR+' from CLIENTBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+@End_Date+char(39)+' AND INOUTFLAG =1 '  
		SELECT @SQLSTR=@SQLSTR+' group by CLIENTID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE on BE.CLIENTID = I.CLIENTID  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select CLIENTID,sum(INAMOUNT) as INAMOUNT   '
		SELECT @SQLSTR=@SQLSTR+' from CLIENTBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+@End_Date +char(39)+'AND INOUTFLAG =-1' 
		SELECT @SQLSTR=@SQLSTR+' group by CLIENTID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE00 on BE00.CLIENTID = I.CLIENTID  '
                          SELECT @SQLSTR=@SQLSTR+'  where     I. CLIENTID in (select CLIENTID from CLIENTBILLFLOW where YYYYMM>='+char(39)+@YYYYMM+char(39)+')'  + @WHERESTING 
	             SELECT @SQLSTR=@SQLSTR+'          order by  I.CLIENTID                '    
------------------------------------------------------------------------
--		       print   @SQLSTR

---		EXEC(@SQLSTR)

	INSERT INTO   #CLIENTTMP    EXEC(@SQLSTR)
	delete  #CLIENTTMP where  EAMOUNT=0



	    declare Cursor_BJ Cursor READ_ONLY for Select CLIENTID  from  #CLIENTTMP  ORDER BY CLIENTID

	    Open Cursor_BJ

	    fetch Cursor_BJ into @CLIENTID


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin


                   ---select @MAXBILLDATE=MAX(BILLDATE) FROM CLIENTbillflow   WHERE  CLIENTID=@CLIENTID
		    select @LastSKDate=max(billdate) from CLIENTBILLFLOW   WHERE  CLIENTID = @CLIENTID and BILLTYPE=4 and YYYYMMBILL=1
		    IF  @LastSKDate IS NULL
		    begin
			set @LastSKDate='2000-10-10'
		    end
	            update   #CLIENTTMP  SET LastSKDate=@LastSKDate WHERE  CLIENTID = @CLIENTID


	    fetch Cursor_BJ into @CLIENTID
 

	    END           ------- Cursor_BJ  WHILE

	    close Cursor_BJ
	    deallocate Cursor_BJ

             SELECT *  FROM #CLIENTTMP   WHERE   EAMOUNT > CREDIT  and (DATEDIFF(day, LastSKDate, getdate())>QiXianDays)



SET QUOTED_IDENTIFIER OFF 
SET ANSI_NULLS ON 

SET QUOTED_IDENTIFIER ON 
SET ANSI_NULLS OFF






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG















CREATE PROCEDURE [CLIENT_CACULATOR_YYYYMM ]  (
	@CLIENTID  varchar(30),
	@YYYYMM  varchar(6)    )
AS 
 
declare @INOUTFLAG NUMERIC(20,10)
declare @INAMOUNT  NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @SUMBAMOUNT NUMERIC(20,10)            ---本期期初总金额
 
BEGIN

            select    @SUMBAMOUNT=isnull(BAMOUNT,0)   FROM   CLIENTBILLFlow  where    (rtrim(CLIENTID) = @CLIENTID) 
						  and (rtrim(YYYYMM) = @YYYYMM) 	and   ( YYYYMMBILL=0   )  
                                       -------以上是期初数据
----------------------------------------------------------------
	    declare CLIENT_CACULATOR Cursor for Select  CLIENTID , isnull(INAMOUNT,0) as INAMOUNT, INOUTFLAG, isnull(EAMOUNT,0) as EAMOUNT 
	                  from CLIENTBILLFlow   where (rtrim(YYYYMM) >= @YYYYMM)  AND ( CLIENTID=@CLIENTID)   and   ( YYYYMMBILL=1   )  
             		      ORDER BY BILLDATE,ID

	    Open CLIENT_CACULATOR

	    fetch CLIENT_CACULATOR into @CLIENTID,@INAMOUNT,@INOUTFLAG,@EAMOUNT


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
		 select    @SUMBAMOUNT=@SUMBAMOUNT+@INAMOUNT*@INOUTFLAG

	         	 UPDATE   CLIENTBILLFLOW  set   EAMOUNT=@SUMBAMOUNT      WHERE CURRENT OF  CLIENT_CACULATOR

		    fetch CLIENT_CACULATOR into @CLIENTID,@INAMOUNT,@INOUTFLAG,@EAMOUNT
 
	    END           ------- CLIENT_CACULATOR  WHILE

	    close CLIENT_CACULATOR
	    deallocate CLIENT_CACULATOR

-----------------------------------------------------------------------------------------------------------------------------------------------------------


END









----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG



















CREATE PROCEDURE [CREAT_QGD]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---是否现款标志
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @VENDORID   varchar(15)               --明细存货编号
declare @Cheng_GoodsName   varchar(50)               --明细存货编号
declare @Cheng_SpecName   varchar(50)               --明细存货编号
declare @bankID   varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @Cai_STOREID varchar(15)               --明细存货编号
declare @GoodsName varchar(50)               --明细存货编号
declare @QieSpecName varchar(50)               --明细存货编号
declare @QieChangDu NUMERIC(20,6)                          --数量
declare @QieKuanDu NUMERIC(20,6)                          --数量
declare @Cai_QieChangDu NUMERIC(20,6)                          --数量
declare @Cai_QieKuanDu NUMERIC(20,6)                          --数量
declare @RATE NUMERIC(20,10)                          --单据总金额
declare @goodsid varchar(15)               --明细存货编号
declare @Cai_GoodsID varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @SUMAMT NUMERIC(20,10)                          --单据总金额
declare @UNITQTY NUMERIC(20,10)                          --单据总金额
declare @StoreQTY NUMERIC(20,10)                          --单据总金额
declare @refqty NUMERIC(20,10)                          --引用数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @ChangCaiFLAG  INTEGER
declare @MeiQty  INTEGER
declare @KeJiaGongQty  INTEGER
declare @PRICETYPE INTEGER
declare @STOREHSFS   INTEGER  --分仓核算

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

set @BILLID   = ltrim(rtrim(@BILLID))

     set @BillDate =   (select BillDate  from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     



if  (select isnull(flagPost,0) from STOREQGDM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_QGD   --事物开始

     set @INOUTFLAG =   (select INOUTFLAG from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @VENDORID =   (select  VENDORID  from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @BANKID =   (select BANKID  from STOREQGDM where rtrim(BILLID) = @BILLID)   ---------付款银行




		delete STOREQGDS  where rtrim(BILLID) = @BILLID

    declare SM_Consign_QGD Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(unitPRICE,0) as PRICE, 
                                                                  DetailBillFlowID,UNITQTY    from STOREQGDD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_QGD

    fetch SM_Consign_QGD into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE, @DetailBillFlowID,@UNITQTY 

    while @@fetch_status = 0            ----开始
    begin



	    select @INF_COSTINGTYPEID=INF_COSTINGTYPEID,@RATE=ISNULL(RATE,0),@QieSpecName=ISNULL(QieSpecName,''),
				@QieChangDu=ISNULL(QieChangDu,0),@QieKuanDu=ISNULL(QieKuanDu,0),
				@GoodsName=Name, @ChangCaiFLAG=ISNULL(ChangCaiFLAG,0),@Cheng_SpecName=SpecName
				from GOODS where  GOODSID = @GOODSID
	--------以上为成品参数 ，材料参数采用CaiLiao开头的变量

			set @Cheng_GoodsName=@GoodsName
-----分两步完成，第一步先把相匹配的材料选出，提取库存，第二部、利用递减法生成有效的记录


		    declare SM_Consign_QGD_00 Cursor for Select  GOODSID,QieChangDu,QieKuanDu   from Goods where @GoodsName=Name and @ChangCaiFLAG=ISNULL(ChangCaiFLAG,0) and @QieSpecName=ISNULL(QieSpecName,'')

		    Open SM_Consign_QGD_00

		    fetch SM_Consign_QGD_00 into @Cai_GoodsID,@Cai_QieChangDu,@Cai_QieKuanDu

		    while @@fetch_status = 0            ----开始
		    begin


----------------每个材料切割成品个数  
				select  @MeiQty=FLOOR(@Cai_QieChangDu/@QieChangDu)

				if @ChangCaiFLAG=0
				begin
				select  @MeiQty=FLOOR(@Cai_QieChangDu/@QieChangDu)*FLOOR(@Cai_QieKuanDu/@QieKuanDu)
				end
---				print @MeiQty

			    declare SM_Consign_QGD_11 Cursor for Select  distinct StoreID   from DetailBillFlow  where GoodsID=@Cai_GoodsID

			    Open SM_Consign_QGD_11
	
			    fetch SM_Consign_QGD_11 into @Cai_StoreID

			    while @@fetch_status = 0            ----开始
			    begin


                            	 EXEC   GETGOODSIDMEQTY  @Cai_StoreID,@Cai_GoodsID,@YYYYMM,@MEQTY=@StoreQTY   OUTPUT

				     set  @KeJiaGongQty=@StoreQTY*@MeiQty

				IF  @StoreQTY>0  and @MeiQty>0
				Begin
		                 execute  GETKEYVALUE     'STOREQGDS',@R_KeyValue = @NEWID output
				    insert into STOREQGDS 
				    (BILLID,ITEMNO,GOODSID,StoreID,StoreQTY,KeJiaGongQty,MeiQty,REITEMNO,Cheng_GoodsID,Cheng_UnitQTY,
					UNITQTY,
					Cheng_GoodsName,Cheng_SpecName)
				    Values
				    (@BillID,@NEWID,@Cai_GoodsID,@Cai_StoreID,@StoreQTY,@KeJiaGongQty,@MeiQty,@ITEMNO,@GoodsID,@UnitQTY,
					FLOOR(@UnitQTY/@MeiQty)+1,
					@Cheng_GoodsName,@Cheng_SpecName)
				end
			
				    fetch SM_Consign_QGD_11 into @Cai_StoreID
	
			    END           ------- SM_Consign_QGD_00  WHILE

			    close SM_Consign_QGD_11
			    deallocate SM_Consign_QGD_11



		    fetch SM_Consign_QGD_00 into @Cai_GoodsID,@Cai_QieChangDu,@Cai_QieKuanDu

		    END           ------- SM_Consign_QGD_00  WHILE

		    close SM_Consign_QGD_00
		    deallocate SM_Consign_QGD_00

	update STOREQGDS   set unitqty=StoreQTY     where rtrim(BILLID) = @BILLID  and MeiQty=1  and cheng_UnitQty>=StoreQTY



--------------------
    fetch SM_Consign_QGD into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE, @DetailBillFlowID,@UNITQTY 

    END           ------- SM_Consign_QGD  WHILE

    close SM_Consign_QGD
    deallocate SM_Consign_QGD

    

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_QGD
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_QGD
      set @flagreturn = 0
   end
end















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG








--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------

CREATE PROCEDURE [CREAT_STRING_BILLNAME]                         --APSOFTENCRYPTION       WITH ENCRYPTION 
 AS                 


declare @BILLTYPEID varchar(30)                   --会计年月     
declare @NAME varchar(30)                   --单句会计年月     
declare @BILLFLAG varchar(15)               --明细存货编号    
declare @CCSTRING     Nvarchar(250)                   --会计年月     


Create Table #temptable10000
      (
   CCSTRING  nvarchar(250)  NULL
		)



    declare SM_Consign_XSCK_DEL Cursor for Select BILLTYPEID,NAME,BILLFLAG   from BILLNAME

    Open SM_Consign_XSCK_DEL

    fetch SM_Consign_XSCK_DEL into @BILLTYPEID,@NAME,@BILLFLAG 

    while @@fetch_status = 0            ----开始
    begin
                 SET @CCSTRING= '  INSERT  BILLNAME  (BILLTYPEID,NAME,BILLFLAG) '
                  SET @CCSTRING=@CCSTRING+'   Values  ( '+CHAR(39)+@BILLTYPEID+CHAR(39)+','+CHAR(39)+@NAME+CHAR(39)+','+CHAR(39)+@BILLFLAG+CHAR(39)+')'
                 INSERT  #temptable10000     Values  (@CCSTRING)
--------------------
      fetch SM_Consign_XSCK_DEL into @BILLTYPEID,@NAME,@BILLFLAG 

    END           ------- SM_Consign_XSCK_DEL  WHILE

    close SM_Consign_XSCK_DEL
    deallocate SM_Consign_XSCK_DEL
     
  SELECT * FROM  #temptable10000  WHERE   CCSTRING  IS  NOT NULL
   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------




----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG





















--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------

CREATE PROCEDURE [CREAT_STRING_BillSeeAbout]                         --APSOFTENCRYPTION       WITH ENCRYPTION 

 AS                 


declare @BillSeeAboutID varchar(6)                  
declare @PageControl varchar(6)                     
declare @STR varchar(15)               
declare @SunXu varchar(8)
declare @STORECGRKM varchar(8)                     
declare @STORECGTHM    varchar(15)
declare @STOREGJRKM varchar(8)              
declare @STORECGFKM   varchar(30)                     
declare @STOREXSCKM    Nvarchar(10)                   
declare @STOREXSTHM   Nvarchar(30)                 
declare @STOREXSSKM    Nvarchar(10) 
declare @STOREQTRKM    Nvarchar(10)
declare @STOREQTCKM    Nvarchar(10)
declare @STORECKDBM    Nvarchar(10)
declare @STORECKPDM    Nvarchar(10)
declare @STOREQTSRM    Nvarchar(10)
declare @STOREFYKZM    Nvarchar(10)
declare @STOREMOVEM    Nvarchar(10)
declare @STORECSHM   Nvarchar(10)                           
declare @STOREYunFeiFKM   Nvarchar(10)                           
declare @STOREXSDDM   Nvarchar(10)                           
declare @STORECGFPM   Nvarchar(10)                           
declare @STOREXSFPM   Nvarchar(10)                           
declare @STOREJGDM   Nvarchar(10)                           
declare @STOREQGDM   Nvarchar(10)                           
declare @STOREQGADM   Nvarchar(10)                           
declare @STORECGDDM   Nvarchar(10)                           
declare @CCSTRING11   Nvarchar(250)   
declare @CCSTRING22   Nvarchar(250)   
declare @CCSTRING33   Nvarchar(250)   


Create Table #temptable10000
      (
  CCSTRING  nvarchar(250)  NULL
		)



    declare SM_Consign_XSCK_DEL Cursor for Select BillSeeAboutID,PageControl,STR,SunXu,STORECGRKM,STORECGTHM,STOREGJRKM,STORECGFKM,STOREXSCKM,STOREXSTHM,STOREXSSKM,STOREQTRKM,STOREQTCKM,STORECKDBM,STORECKPDM,STOREQTSRM,STOREFYKZM,STOREMOVEM,STORECSHM,STOREYunFeiFKM,STOREXSDDM,STORECGFPM,STOREXSFPM,STOREQGADM,STORECGDDM,STOREJGDM,STOREQGDM   from BillSeeAbout

    Open SM_Consign_XSCK_DEL

    fetch SM_Consign_XSCK_DEL into @BillSeeAboutID,@PageControl,@STR,@SunXu,@STORECGRKM,@STORECGTHM,@STOREGJRKM,@STORECGFKM,@STOREXSCKM,@STOREXSTHM,@STOREXSSKM,@STOREQTRKM,@STOREQTCKM,@STORECKDBM,@STORECKPDM,@STOREQTSRM,@STOREFYKZM,@STOREMOVEM,@STORECSHM,@STOREYunFeiFKM,@STOREXSDDM,@STORECGFPM,@STOREXSFPM,@STOREQGADM,@STORECGDDM,@STOREJGDM,@STOREQGDM

    while @@fetch_status = 0            ----开始
    begin
                 SET @CCSTRING11= '  INSERT  BillSeeAbout (PageControl,STR,SunXu,STORECGRKM,STORECGTHM,STOREGJRKM,STORECGFKM,STOREXSCKM,STOREXSTHM,STOREXSSKM,STOREQTRKM, '
                 INSERT  #temptable10000     Values  (@CCSTRING11)
                 SET @CCSTRING22= '    STOREQTCKM,STORECKDBM,STORECKPDM,STOREQTSRM,STOREFYKZM,STOREMOVEM,STORECSHM,STOREYunFeiFKM,STOREXSDDM,STORECGFPM,STOREXSFPM,STOREQGADM,STORECGDDM,STOREJGDM,STOREQGDM) '
                 INSERT  #temptable10000     Values  (@CCSTRING22)
                  SET @CCSTRING33='   Values ( '+CHAR(39)+@PageControl+CHAR(39)+','+CHAR(39)+@STR+CHAR(39)+','+CHAR(39)+@SunXu+CHAR(39)+','+CHAR(39)+@STORECGRKM+CHAR(39)+','+CHAR(39)+@STORECGTHM+CHAR(39)+','+CHAR(39)+@STOREGJRKM+CHAR(39)+','+CHAR(39)+@STORECGFKM+CHAR(39)+','+CHAR(39)+@STOREXSCKM+CHAR(39)+','+CHAR(39)+@STOREXSTHM+CHAR(39)+','+CHAR(39)+@STOREXSSKM+CHAR(39)+','+CHAR(39)+@STOREQTRKM+CHAR(39)+','+CHAR(39)+@STOREQTCKM+CHAR(39)+','+CHAR(39)+@STORECKDBM+CHAR(39)+','+CHAR(39)+@STORECKPDM+CHAR(39)+','+CHAR(39)+@STOREQTSRM+CHAR(39)+','+CHAR(39)+@STOREFYKZM+CHAR(39)+','+CHAR(39)+@STOREMOVEM+CHAR(39)+','+CHAR(39)+@STORECSHM+CHAR(39)+','+CHAR(39)+@STOREYunFeiFKM+CHAR(39)+','+CHAR(39)+@STOREXSDDM+CHAR(39)+','+CHAR(39)+@STORECGFPM+CHAR(39)+','+CHAR(39)+@STOREXSFPM+CHAR(39)+','+CHAR(39)+@STOREQGADM+CHAR(39)+','+CHAR(39)+@STORECGDDM+CHAR(39)+','+CHAR(39)+@STOREJGDM+CHAR(39)+','+CHAR(39)+@STOREQGDM+CHAR(39)+')'
                 INSERT  #temptable10000     Values  (@CCSTRING33)
--------------------
    fetch SM_Consign_XSCK_DEL into @BillSeeAboutID,@PageControl,@STR,@SunXu,@STORECGRKM,@STORECGTHM,@STOREGJRKM,@STORECGFKM,@STOREXSCKM,@STOREXSTHM,@STOREXSSKM,@STOREQTRKM,@STOREQTCKM,@STORECKDBM,@STORECKPDM,@STOREQTSRM,@STOREFYKZM,@STOREMOVEM,@STORECSHM,@STOREYunFeiFKM,@STOREXSDDM,@STORECGFPM,@STOREXSFPM,@STOREQGADM,@STORECGDDM,@STOREJGDM,@STOREQGDM

    END           ------- SM_Consign_XSCK_DEL  WHILE

    close SM_Consign_XSCK_DEL
    deallocate SM_Consign_XSCK_DEL
     
  SELECT * FROM  #temptable10000  WHERE   CCSTRING  IS  NOT NULL
   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------











----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------

CREATE PROCEDURE [CREAT_STRING_FunctionM]                         --APSOFTENCRYPTION       WITH ENCRYPTION 
 AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @REDetailBillFlowID   varchar(30)                     --序列号
declare @Function_Id    Nvarchar(10)                   --会计年月     
declare @Function_Desc   Nvarchar(30)                   --会计年月     
declare @Program_Name    Nvarchar(10)                   --会计年月     
declare @Parent_Function_Id   Nvarchar(10)                   --会计年月     
declare @Control_Owner   Nvarchar(30)                   --会计年月     
declare @Control_Name    Nvarchar(30)                   --会计年月     
declare @Control_Type   Nvarchar(30)                   --会计年月     
declare @CCSTRING     Nvarchar(250)                   --会计年月     


Create Table #temptable10000
      (
   CCSTRING  nvarchar(250)  NULL
		)



    declare SM_Consign_XSCK_DEL Cursor for Select Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type   from FunctionM

    Open SM_Consign_XSCK_DEL

    fetch SM_Consign_XSCK_DEL into @Function_Id,@Parent_Function_Id,@Program_Name,@Function_Desc,@Control_Owner,@Control_Name,@Control_Type 

    while @@fetch_status = 0            ----开始
    begin
                 SET @CCSTRING= '  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type) '
                  SET @CCSTRING=@CCSTRING+'   Values  ( '+CHAR(39)+@Function_Id+CHAR(39)+','+CHAR(39)+@Parent_Function_Id+CHAR(39)+','+CHAR(39)+@Program_Name+CHAR(39)+','+CHAR(39)+@Function_Desc+CHAR(39)+','+CHAR(39)+@Control_Owner+CHAR(39)+','+CHAR(39)+@Control_Name+CHAR(39)+','+CHAR(39)+@Control_Type+CHAR(39)+')'
                 INSERT  #temptable10000     Values  (@CCSTRING)
--------------------
      fetch SM_Consign_XSCK_DEL into  @Function_Id,@Parent_Function_Id,@Program_Name,@Function_Desc,@Control_Owner,@Control_Name,@Control_Type 

    END           ------- SM_Consign_XSCK_DEL  WHILE

    close SM_Consign_XSCK_DEL
    deallocate SM_Consign_XSCK_DEL
     
  SELECT * FROM  #temptable10000  WHERE   CCSTRING  IS  NOT NULL
   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------




----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------

CREATE PROCEDURE [CREAT_STRING_SETCOL]                         --APSOFTENCRYPTION       WITH ENCRYPTION 

 AS                 


declare @FEILDNAME varchar(30)                  
declare @lEN varchar(30)                     
declare @CHINESENAME varchar(30)               
declare @FABC varchar(10)
declare @FGROUP varchar(30)
declare @ProgramName varchar(20)                     
declare @BILLNAME    varchar(30)
declare @HAVEGROUP varchar(20)              
declare @SHOWFLAG   varchar(30)                     
declare @ID   varchar(30)                     
declare @QSLEN    Nvarchar(10)                   
declare @QSCHINESENAME   Nvarchar(30)                 
declare @QSSHOWFLAG    Nvarchar(10)                               
declare @CCSTRING   Nvarchar(250)   


Create Table #temptable10000
      (
  CCSTRING  nvarchar(250)  NULL
		)



    declare SM_Consign_XSCK_DEL Cursor for Select FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG   from SETCOL

    Open SM_Consign_XSCK_DEL

    fetch SM_Consign_XSCK_DEL into @FEILDNAME,@lEN,@CHINESENAME,@FABC,@FGROUP,@ProgramName,@BILLNAME,@HAVEGROUP,@SHOWFLAG,@ID,@QSLEN,@QSCHINESENAME,@QSSHOWFLAG

    while @@fetch_status = 0            ----开始
    begin
	IF @FGROUP IS NULL
	BEGIN
                 SET @CCSTRING= '  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG) '
                  SET @CCSTRING=@CCSTRING+'   Values  ( '+CHAR(39)+@FEILDNAME+CHAR(39)+', '+CHAR(39)+@lEN+CHAR(39)+','+CHAR(39)+@CHINESENAME+CHAR(39)+','+CHAR(39)+@FABC+CHAR(39)+','+CHAR(39)+@ProgramName+CHAR(39)+','+CHAR(39)+@BILLNAME+CHAR(39)+','+@HAVEGROUP+','+CHAR(39)+@SHOWFLAG+CHAR(39)+','+CHAR(39)+@ID+CHAR(39)+','+CHAR(39)+@QSLEN+CHAR(39)+','+CHAR(39)+@QSCHINESENAME+CHAR(39)+','+CHAR(39)+@QSSHOWFLAG+CHAR(39)+')'
	END
	ELSE
	BEGIN
                  SET @CCSTRING= '  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG) '
                  SET @CCSTRING=@CCSTRING+'   Values  ( '+CHAR(39)+@FEILDNAME+CHAR(39)+', '+CHAR(39)+@lEN+CHAR(39)+','+CHAR(39)+@CHINESENAME+CHAR(39)+','+CHAR(39)+@FABC+CHAR(39)+','+CHAR(39)+@FGROUP+CHAR(39)+','+CHAR(39)+@ProgramName+CHAR(39)+','+CHAR(39)+@BILLNAME+CHAR(39)+','+CHAR(39)+@HAVEGROUP+CHAR(39)+','+CHAR(39)+@SHOWFLAG+CHAR(39)+','+CHAR(39)+@ID+CHAR(39)+','+CHAR(39)+@QSLEN+CHAR(39)+','+CHAR(39)+@QSCHINESENAME+CHAR(39)+','+CHAR(39)+@QSSHOWFLAG+CHAR(39)+')'
	END
                 INSERT  #temptable10000     Values  (@CCSTRING)
--------------------
      fetch SM_Consign_XSCK_DEL into @FEILDNAME,@lEN,@CHINESENAME,@FABC,@FGROUP,@ProgramName,@BILLNAME,@HAVEGROUP,@SHOWFLAG,@ID,@QSLEN,@QSCHINESENAME,@QSSHOWFLAG

    END           ------- SM_Consign_XSCK_DEL  WHILE

    close SM_Consign_XSCK_DEL
    deallocate SM_Consign_XSCK_DEL
     
  SELECT * FROM  #temptable10000  WHERE   CCSTRING  IS  NOT NULL
   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------




----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------

CREATE PROCEDURE [CREAT_STRING_Sys_DictTable]                         --APSOFTENCRYPTION       WITH ENCRYPTION 

 AS                 


declare @TableName varchar(20)                  
declare @FieldName varchar(20)                     
declare @FieldType varchar(15)               
declare @ChineseName varchar(20)                     
declare @ChineseTableName    varchar(30)              
declare @SystemName   varchar(30)                     
declare @FieldOrder   varchar(30)                     
declare @Remark    Nvarchar(10)                   
declare @FieldSize   Nvarchar(30)                 
declare @ExeclIn    Nvarchar(10)                          
declare @EXECLINMUST   Nvarchar(10)                          
declare @CCSTRING11   Nvarchar(250)   
declare @CCSTRING22   Nvarchar(250)   


Create Table #temptable10000
      (
  CCSTRING  nvarchar(250)  NULL
		)



    declare SM_Consign_XSCK_DEL Cursor for Select TableName,FieldName,FieldType,ChineseName,ChineseTableName,SystemName,FieldOrder,Remark,FieldSize,ExeclIn,EXECLINMUST   from Sys_DictTable  where TableName in ('GOODS','VENDOR','CLIENT')  AND EXECLIN=1

    Open SM_Consign_XSCK_DEL

    fetch SM_Consign_XSCK_DEL into @TableName,@FieldName,@FieldType,@ChineseName,@ChineseTableName,@SystemName,@FieldOrder,@Remark,@FieldSize,@ExeclIn,@EXECLINMUST

    while @@fetch_status = 0            ----开始
    begin
                 SET @CCSTRING11= '  INSERT  Sys_DictTable  (TableName,FieldName,FieldType,ChineseName,ChineseTableName,SystemName,FieldOrder,Remark,FieldSize,ExeclIn,EXECLINMUST) '
                 INSERT  #temptable10000     Values  (@CCSTRING11)
                  SET @CCSTRING22='   Values  ( '+CHAR(39)+@TableName+CHAR(39)+', '+CHAR(39)+@FieldName+CHAR(39)+','+CHAR(39)+@FieldType+CHAR(39)+','+CHAR(39)+@ChineseName+CHAR(39)+','+CHAR(39)+@ChineseTableName+CHAR(39)+','+CHAR(39)+@SystemName+CHAR(39)+','+CHAR(39)+@FieldOrder+CHAR(39)+','+CHAR(39)+@Remark+CHAR(39)+','+CHAR(39)+@FieldSize+CHAR(39)+','+CHAR(39)+@ExeclIn+CHAR(39)+','+CHAR(39)+@EXECLINMUST+CHAR(39)+')'
                 INSERT  #temptable10000     Values  (@CCSTRING22)
--------------------
    fetch SM_Consign_XSCK_DEL into @TableName,@FieldName,@FieldType,@ChineseName,@ChineseTableName,@SystemName,@FieldOrder,@Remark,@FieldSize,@ExeclIn,@EXECLINMUST

    END           ------- SM_Consign_XSCK_DEL  WHILE

    close SM_Consign_XSCK_DEL
    deallocate SM_Consign_XSCK_DEL
     
  SELECT * FROM  #temptable10000  WHERE   CCSTRING  IS  NOT NULL
--  SELECT * FROM  #temptable10000  
   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------




----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG


















--------------------------------------------------------------------

CREATE PROCEDURE CW_BETWEEN_CURR_YYYYMM  
                 (
                  @BILLDATE DATEtime,
                  @flagreturn int output,     ---返回记帐成功  -- 0 不在此会计期间  --1 在会计期间
                  @BillYYYYMMreturn VARCHAR(10) output     ---返回记帐成功  -- 0 不在此会计期间  --1 在会计期间
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     

declare @MINBILLDATE DATEtime
declare @MAXBILLDATE DATEtime
declare @PRODUCTDATE DATEtime
declare @Next_YYYYMMDate DATEtime
declare @B_ID INTEGER
declare @STOREHSFS   INTEGER

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

     select @flagreturn = 1     

   declare  @PREV_YYYYMM          varchar(6)  -- 上一个会计年月
   declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='CW_YYYYMM')  

   
	if substring(@YYYYMM,5,2) = '12'  --- 如果当前会计月等于最大的会计月，将需要转入下年的的第一个会计年月
	begin
	    set @Next_YYYYMM   = convert(varchar,convert(int,substring(@YYYYMM,1,4))+1) +'01'  
	end
	else
	begin
	    set @Next_YYYYMM   = substring(@YYYYMM,1,4) +substring('00',1,2-len(convert(varchar,convert(int,substring(@YYYYMM,5,2))+1)))+convert(varchar,convert(int,substring(@YYYYMM,5,2))+1)
	end

	if substring(@YYYYMM,5,2) = '01'  --- 如果当前会计月等于最大的会计月，将需要转入下年的的第一个会计年月
	begin
	    set @PREV_YYYYMM   = convert(varchar,convert(int,substring(@YYYYMM,1,4))-1) +'12'  
	end
	else
	begin
	    set @PREV_YYYYMM   = substring(@YYYYMM,1,4) +substring('00',1,2-len(convert(varchar,convert(int,substring(@YYYYMM,5,2))-1)))+convert(varchar,convert(int,substring(@YYYYMM,5,2))-1)
	end

	declare @YYYYMMFS INTEGER
	declare @YYYYMMFSDATE  INTEGER
	declare @Billday  INTEGER

	       SELECT    @YYYYMMFS =(SELECT  YYYYMMFS   FROM   ACCINFO    WHERE   GUID='0001' )    
                IF @YYYYMMFS=1
	  BEGIN
		     SET  @MINBillDate = CONVERT(DATEtime,@YYYYMM+'01')
		     SET  @MAXBillDate =CONVERT(DATEtime,@Next_YYYYMM+'01')
		     set @BillYYYYMMreturn=convert(varchar,DATEPART(year,@BillDate))+substring('00',1,2-len(convert(varchar,DATEPART(month,@BillDate))))+convert(varchar,DATEPART(month,@BillDate))
	  END
               ELSE
               BEGIN
	       SELECT    @YYYYMMFSDATE =(SELECT  YYYYMMFSDATE   FROM   ACCINFO    WHERE   GUID='0001' )    
       
	     SET  @MINBillDate =DATEADD(day, @YYYYMMFSDATE, CONVERT(DATEtime,@PREV_YYYYMM+'01'))
	     SET  @MAXBillDate =DATEADD(day, @YYYYMMFSDATE, CONVERT(DATEtime,@YYYYMM+'01'))
        	SELECT @Billday =DATEPART(day, @BillDate)
		if @Billday> @YYYYMMFSDATE  -----分界线
		begin
		     set @BillYYYYMMreturn=convert(varchar,DATEPART(year,DATEADD(month,1,@BillDate)))+substring('00',1,2-len(convert(varchar,DATEPART(month,DATEADD(month,1,@BillDate)))))+convert(varchar,DATEPART(month,DATEADD(month,1,@BillDate)))
		end
		else
		begin
		     set @BillYYYYMMreturn=convert(varchar,DATEPART(year,@BillDate))+substring('00',1,2-len(convert(varchar,DATEPART(month,@BillDate))))+convert(varchar,DATEPART(month,@BillDate))
		end



	 END

----      IF (@BillDate<@MINBillDate)  OR (@BillDate>=@MAXBillDate)
----可以记账当前会计期间以后的单据
      IF (@BillDate<@MINBillDate)  
      BEGIN
      set @flagreturn = 0
      RETURN
      END









----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG















CREATE PROCEDURE [dbo].[CW_BILL_XuHao_ChongPai](
                  @TableName varchar(50),      ---单据编号   
                  @BILLID varchar(22)      ---单据编号   

)  
AS 
 
declare @YYYYMM  varchar(10)
declare @ITEMNO  varchar(10)
declare @INAMOUNT  NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @SUMBAMOUNT NUMERIC(20,10)            ---本期期初总金额
declare     @RETURNSTRINGXX    varchar(60)   
declare     @XuHao int 
 
BEGIN


----exec CW_BILL_XuHao_ChongPai 'STORECW_LRBMBD' ,'00000007'

    IF @TableName='STORECW_LRBMBD'
    begin

	    set @XuHao=1	
	    declare CW_BILL_XuHao_ChongPai_Cursor Cursor for Select ItemNO from STORECW_LRBMBD   where BILLID = @BILLID
            		      ORDER BY ItemNO

	    Open CW_BILL_XuHao_ChongPai_Cursor

	    fetch CW_BILL_XuHao_ChongPai_Cursor into @ItemNO


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin

		    update STORECW_LRBMBD set   xuhao=@xuhao   where ItemNO=@ItemNO
		    set @XuHao=@XuHao+1	

		    fetch CW_BILL_XuHao_ChongPai_Cursor into @ItemNO
 
	    END           ------- CW_BILL_XuHao_ChongPai_Cursor  WHILE

	    close CW_BILL_XuHao_ChongPai_Cursor
	    deallocate CW_BILL_XuHao_ChongPai_Cursor

    end

-----------------------------------------------------------------------------------------------------------------------------------------------------------
    IF @TableName='STORECW_ZCFZBMBD'
    begin

	    set @XuHao=1	
	    declare CW_BILL_XuHao_ChongPai_Cursor Cursor for Select ItemNO from STORECW_ZCFZBMBD   where BILLID = @BILLID
            		      ORDER BY ItemNO

	    Open CW_BILL_XuHao_ChongPai_Cursor

	    fetch CW_BILL_XuHao_ChongPai_Cursor into @ItemNO


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin

		    update STORECW_ZCFZBMBD set   xuhao=@xuhao   where ItemNO=@ItemNO
		    set @XuHao=@XuHao+1	

		    fetch CW_BILL_XuHao_ChongPai_Cursor into @ItemNO
 
	    END           ------- CW_BILL_XuHao_ChongPai_Cursor  WHILE

	    close CW_BILL_XuHao_ChongPai_Cursor
	    deallocate CW_BILL_XuHao_ChongPai_Cursor

    end

-----------------------------------------------------------------------------------------------------------------------------------------------------------
    IF @TableName='STORECW_XJLLBMBD'
    begin

	    set @XuHao=1	
	    declare CW_BILL_XuHao_ChongPai_Cursor Cursor for Select ItemNO from STORECW_XJLLBMBD   where BILLID = @BILLID
            		      ORDER BY ItemNO

	    Open CW_BILL_XuHao_ChongPai_Cursor

	    fetch CW_BILL_XuHao_ChongPai_Cursor into @ItemNO


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin

		    update STORECW_XJLLBMBD set   xuhao=@xuhao   where ItemNO=@ItemNO
		    set @XuHao=@XuHao+1	

		    fetch CW_BILL_XuHao_ChongPai_Cursor into @ItemNO
 
	    END           ------- CW_BILL_XuHao_ChongPai_Cursor  WHILE

	    close CW_BILL_XuHao_ChongPai_Cursor
	    deallocate CW_BILL_XuHao_ChongPai_Cursor

    end

-----------------------------------------------------------------------------------------------------------------------------------------------------------



END






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













--------------------------------------------------------------------插入月结记录

CREATE PROCEDURE [dbo].[CW_BillFlow_insert_YYYYMM]  
                 (	
	@ItemBM varchar(30)
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @VENDORFLAG int           ---单据类型
declare @NEWID varchar(15)               --明细存货编号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @B_CODE VARCHAR(25)
declare @B_ID INTEGER
declare @Detailflag int           ---单据类型
declare @BenYueLastDay  VARCHAR(10)

--------增加对新增的科目增加所有月结记录
---     set @YYYYMM   = (select optionvalue from accoptions where optionname ='CW_YYYYMM') 


     declare CW_BillFlow_YYYYMM Cursor for     Select  Distinct YYYYMM from CW_BillFlow  

	    Open CW_BillFlow_YYYYMM

	    fetch CW_BillFlow_YYYYMM into @YYYYMM 


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin



		     Select @BenYueLastDay =CONVERT(varchar(100), dateadd(dd,-1,dateadd(m,1,Substring(@YYYYMM,1,4)+'-'+Substring(@YYYYMM,5,2)+'-01')), 23)

      
		     select @Detailflag=Detailflag from ItemInfo where ItemBM=@ItemBM


	            IF not exists(select *  from CW_BILLFLOW  where 
             		                                    (rtrim(ItemBM) = @ItemBM)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 )       
	            BEGIN
                     execute  GETKEYVALUE     'CW_BillFlow',@R_KeyValue = @NEWID output
		    insert into CW_BillFlow 
		    (ID,YYYYMM,YYYYMMBILL,ItemBM,
		     BAMOUNT,debit,credit,EAMOUNT,Detailflag,brief,BILLDATE,XuHao)
		    Values
		    (@NEWID,@YYYYMM,0,@ItemBM,0,0,0,0,@Detailflag,'本期合计',@BenYueLastDay,'88888888')  
	            END      ------IF   END

------------------------------------------------------------------------------
	            IF not exists(select *  from CW_BILLFLOW  where 
             		                                    (rtrim(ItemBM) = @ItemBM)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 2)       ---2代表本期合计记录
             		                                 )       
	            BEGIN
                     execute  GETKEYVALUE     'CW_BillFlow',@R_KeyValue = @NEWID output
		    insert into CW_BillFlow 
		    (ID,YYYYMM,YYYYMMBILL,ItemBM,
		     BAMOUNT,debit,credit,EAMOUNT,Detailflag,brief,BILLDATE,XuHao)
		    Values
		    (@NEWID,@YYYYMM,2,@ItemBM,0,0,0,0,@Detailflag,'本年累计',@BenYueLastDay,'99999999')
	            END      ------IF   END

----------------------------------------------------------------------------------
/*	            IF not exists(select *  from CW_BILLFLOW  where 
             		                                    (rtrim(ItemBM) = @ItemBM)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 3)       ---3代表会计科目初始化本年累计记录
             		                                 )       
	            BEGIN
                     execute  GETKEYVALUE     'CW_BillFlow',@R_KeyValue = @NEWID output
		    insert into CW_BillFlow 
		    (ID,YYYYMM,YYYYMMBILL,ItemBM,
		     BAMOUNT,debit,credit,EAMOUNT,Detailflag)
		    Values
		    (@NEWID,@YYYYMM,3,@ItemBM,0,0,0,0,@Detailflag)    
	            END      ------IF   END

*/

		    fetch CW_BillFlow_YYYYMM into @YYYYMM
 
	    END           ------- CW_BillFlow_YYYYMM  WHILE

	    close CW_BillFlow_YYYYMM
	    deallocate CW_BillFlow_YYYYMM
		

SET QUOTED_IDENTIFIER OFF






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG















CREATE PROCEDURE [dbo].[CW_CACULATOR_YYYYMM ]  (
	@ItemBM  varchar(30),
	@YYYYMM  varchar(6)    )
AS 
 
declare @Debit  NUMERIC(20,2)
declare @Credit NUMERIC(20,2)
declare @EAMOUNT NUMERIC(20,2)
declare @SUMBAMOUNT NUMERIC(20,2)            ---本期期初总金额
declare @JHD int

 
BEGIN


		select @JHD =JHD from ItemInfo where rtrim(ItemBM) = @ItemBM

            select    @SUMBAMOUNT=isnull(BAMOUNT,0)   FROM   CW_BILLFlow  where    (rtrim(ItemBM) = @ItemBM) 
						  and (rtrim(YYYYMM) = @YYYYMM) 	and   ( YYYYMMBILL=0   )  

                                       -------以上是期初数据
----------------------------------------------------------------
	    declare CW_CACULATOR Cursor for Select  ItemBM , isnull(Debit,0) as Debit, isnull(Credit,0) as Credit, isnull(EAMOUNT,0) as EAMOUNT 
	                  from CW_BILLFlow   where (rtrim(YYYYMM) >= @YYYYMM)  AND ( ItemBM=@ItemBM)   and   ( YYYYMMBILL=1   )  
             		      ORDER BY BILLDATE,ID

	    Open CW_CACULATOR

	    fetch CW_CACULATOR into @ItemBM,@Debit,@Credit,@EAMOUNT


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
		 select    @SUMBAMOUNT=@SUMBAMOUNT+(@Debit-@Credit)*@JHD
--		print @JHD
--		 select    @SUMBAMOUNT=@SUMBAMOUNT+@Debit-@Credit

	         	 UPDATE   CW_BILLFlow  set   EAMOUNT=@SUMBAMOUNT      WHERE CURRENT OF  CW_CACULATOR

		    fetch CW_CACULATOR into @ItemBM,@Debit,@Credit,@EAMOUNT
 
	    END           ------- CW_CACULATOR  WHILE

	    close CW_CACULATOR
	    deallocate CW_CACULATOR

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------解决本期合计

			update CW_BILLFLOW   set  Debit=( select isnull(sum(Debit),0) from  CW_BILLFLOW
                                    where ItemBM = @ItemBM and(rtrim(YYYYMMBILL) = 1)  and (rtrim(YYYYMM) = @YYYYMM)  ) ,
						  Credit=( select isnull(sum(Credit),0) from  CW_BILLFLOW
                                    where ItemBM = @ItemBM and(rtrim(YYYYMMBILL) = 1) and (rtrim(YYYYMM) = @YYYYMM) )  					  						       
					        where    (rtrim(ItemBM) = @ItemBM)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)

			update CW_BILLFLOW   set  EAMOUNT=isnull(BAMOUNT,0)+(isnull(Debit,0)-isnull(Credit,0))*@JHD
					        where    (rtrim(ItemBM) = @ItemBM)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)
-------------------------------------------------------------------------------------------------
-----------------------解决本年累计

			update CW_BILLFLOW   set  Debit=( select isnull(sum(Debit),0) from  CW_BILLFLOW
                                    where ItemBM = @ItemBM and(rtrim(YYYYMMBILL) in (1,3)) ) ,
						  Credit=( select isnull(sum(Credit),0) from  CW_BILLFLOW
                                    where ItemBM = @ItemBM and(rtrim(YYYYMMBILL) in (1,3)) )  					  						       
					        where    (rtrim(ItemBM) = @ItemBM)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 2)



END











----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG







-------------2006.01.23  修改为不传递会计期间进行月末结帐

-------------------------------------------------------------------

CREATE PROCEDURE [dbo].[CW_DataToNext] (
                              @IsSuccess         int output     ---返回成功  -- 0 不成功  --1 
                            )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
Begin transaction CWDataToNext
declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月
declare  @SQLSTR         varchar(8000)  -- 下一个会计年月
declare         @Current_YYYYMM  varchar(20)   --传入当前会计期间


declare @YYYYMM varchar(6)                   --会计年月     

declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)

declare @YYYYMMBILL int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @CLIENTID varchar(15)               --明细存货
declare @VENDORID varchar(15)               --明细存货编号
declare @BANKID varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @Bqty NUMERIC(20,10)                          --数量
declare @BAMOUNT NUMERIC(20,10)                          --数量
declare @Eqty NUMERIC(20,10)                          --数量
declare @EAMOUNT NUMERIC(20,10)                          --数量



declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @B_ID INTEGER
declare @BenYueLastDay  VARCHAR(10)

     set  @Current_YYYYMM   = (select optionvalue from accoptions where optionname ='CW_YYYYMM') 
    

if substring(@Current_YYYYMM,5,2) = '12'  --- 如果当前会计月等于最大的会计月，将需要转入下年的的第一个会计年月
begin
    set @Next_YYYYMM   = convert(varchar,convert(int,substring(@Current_YYYYMM,1,4))+1) +'01'  
end
else
begin
    set @Next_YYYYMM   = substring(@Current_YYYYMM,1,4) +substring('00',1,2-len(convert(varchar,convert(int,substring(@Current_YYYYMM,5,2))+1)))+convert(varchar,convert(int,substring(@Current_YYYYMM,5,2))+1)
end


--------判断当前会计期间是否月结，不能重复月结

	  if exists(Select * from CW_PingZhengM where YYYYMM=@Current_YYYYMM AND ISNULL(FlagPost,0)=0)
	  begin
		   commit transaction CWDataToNext
		   set @IsSuccess=0

	  end

-------declare @flagreturn int 
-------exec STORE_YYYYMM_INSERT   @flagreturn output 
	Select @BenYueLastDay =CONVERT(varchar(100), dateadd(dd,-1,dateadd(m,1,Substring(@Next_YYYYMM,1,4)+'-'+Substring(@Next_YYYYMM,5,2)+'-01')), 23)


--------取得接转当前会计期间的数据并复制到临时表中 begin --------------------------------
	delete  CW_BILLFLOWTMP

        INSERT  INTO   CW_BILLFLOWTMP  Select * from  CW_BILLFLOW where yyyymmbill=0 and YYYYMM=@Current_YYYYMM

        update   CW_BILLFLOWTMP  set YYYYMM=@Next_YYYYMM ,BAMOUNT=EAMOUNT,Debit=0,Credit=0,ID=SubString(ID,1,8)+@Next_YYYYMM,BillDate=@BenYueLastDay

    	INSERT  INTO   CW_BILLFLOW  Select * from  CW_BILLFLOWTMP where yyyymmbill=0


-----------------------
	delete  CW_BILLFLOWTMP

        INSERT  INTO   CW_BILLFLOWTMP  Select * from  CW_BILLFLOW where yyyymmbill=2 and YYYYMM=@Current_YYYYMM

        update   CW_BILLFLOWTMP  set YYYYMM=@Next_YYYYMM ,ID=SubString(ID,1,8)+@Next_YYYYMM,BillDate=@BenYueLastDay

    	INSERT  INTO   CW_BILLFLOW  Select * from  CW_BILLFLOWTMP where yyyymmbill=2

--	delete CW_BILLFLOW where YYYYMM='201309' and yyyymmbill in (0,2)
--      update   accoptionS  set optionvalue='201308'           where optionname ='CW_YYYYMM' 
  update   accoptionS  set optionvalue=@Next_YYYYMM           where optionname ='CW_YYYYMM'
     





--------取得接转当前会计期间的数据并复制到临时表中 end ------------------------------------

--写结转信息
  If @@error = 0
  begin
     commit transaction CWDataToNext
   set @IsSuccess=1
  end
  else
  begin
    rollback transaction CWDataToNext
   set @IsSuccess=0
    raiserror('结转失败 ', 1, 20) 
  end







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG








-------------2006.01.23  修改为不传递会计期间进行取消月末结帐


CREATE PROCEDURE [dbo].[CW_DataToNextDel] (
			 @FlagDel    int ,     ----------删除结转损益产生的凭证
                              @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                              @IsSuccess         int output     ---返回成功  -- 0 不成功  --1 
                            )  --APSOFTENCRYPTION       WITH ENCRYPTION
 AS 
Begin transaction CWDataToNext

   declare  @PREV_YYYYMM          varchar(6)  -- 上一个会计年月
   declare  @Current_YYYYMM          varchar(6)  -- 上一个会计年月
   declare  @GOODSID          varchar(10)  -- 上一个会计年月
   declare  @STOREID         varchar(10)  -- 上一个会计年月
   declare  @CLIENTID         varchar(10)  -- 上一个会计年月
   declare  @VENDORID         varchar(10)  -- 上一个会计年月
   declare  @BANKID         varchar(10)  -- 上一个会计年月
   declare  @BILLID          varchar(10)  -- 上一个会计年月
   declare  @BEGINYYYYMM          varchar(10)  -- 上一个会计年月
declare @RETURNSTRINGXX    varchar(60)   
declare @flagreturnXX int 
declare @ItemBM varchar(20)               --明细存货编号
declare @NewItemBM varchar(20)               --明细存货编号
declare @PrevNO varchar(20)               --明细存货编号
declare @Detailflag   INT
declare @BenNianLRKeMu  varchar(30) 


      SET @RETURNSTRING='  '
     set  @Current_YYYYMM   = (select optionvalue from accoptions where optionname ='CW_YYYYMM')     
	if substring(@Current_YYYYMM,5,2) = '01'  --- 如果当前会计月等于最大的会计月，将需要转入下年的的第一个会计年月
	begin
	    set @PREV_YYYYMM   = convert(varchar,convert(int,substring(@Current_YYYYMM,1,4))-1) +'12'  
	end
	else
	begin
	    set @PREV_YYYYMM   = substring(@Current_YYYYMM,1,4) +substring('00',1,2-len(convert(varchar,convert(int,substring(@Current_YYYYMM,5,2))-1)))+convert(varchar,convert(int,substring(@Current_YYYYMM,5,2))-1)
	end

	IF  NOT (exists (SELECT * FROM CW_BILLFLOW  where YYYYMM=@PREV_YYYYMM)) 

	BEGIN
			      rollback transaction CWDataToNext
			      set @IsSuccess   = 0
                              SET @RETURNSTRING='启用帐套的会计期间不能反结账！'
                              RETURN
	END 

       	 DELETE  CW_BILLFLOW  where YYYYMM=@Current_YYYYMM   and  YYYYMMBILL IN ( 0,1,2)   

  
         update   accoptionS  set optionvalue=@PREV_YYYYMM        where optionname ='CW_YYYYMM'

-----@BenNianLRKeMu='3131'
	select @BenNianLRKeMu=BenNianLRKeMu  FROM  ACCINFO  WHERE GUID='0001'



        IF @FlagDel =1 
	begin

	

	 delete  CW_PingZhengM where BILLID IN (Select BILLID from CW_PingZhengD where ItemBM =@BenNianLRKeMu AND YYYYMM=@PREV_YYYYMM)

       	 DELETE  CW_BILLFLOW  where  YYYYMMBILL=1  and (BILLID NOT IN (Select BILLID from CW_PingZhengD))


		    declare Cursor_CW_DataToNextDel Cursor for Select Itembm from  Iteminfo  where DetailFlag=1 and (Itembm Like '5%' OR  ItemBM =@BenNianLRKeMu) 
								Order By Itembm
		    Open Cursor_CW_DataToNextDel

		    fetch Cursor_CW_DataToNextDel into @Itembm

		    while @@fetch_status = 0            ----开始
		    begin

			    set @NewItemBM=@ItemBM
			
			    select @PrevNO='9999AAAA'

		
			      while  (@PrevNO<>'0000') 
			      begin
			        select @Detailflag=Detailflag from ItemInfo where ItemBM=@NewItemBM

			      execute   CW_CACULATOR_YYYYMM @NewItemBM,@PREV_YYYYMM
	
			        select @PrevNO=PrevNO from ItemInfo where ItemBM=@NewItemBM


				SET @NewItemBM=@PrevNO
		
			     end          -------while  @PrevNO<>'0000' 



		    fetch Cursor_CW_DataToNextDel into @Itembm

		    END           ------- Cursor_CW_DataToNextDel  WHILE

		    close Cursor_CW_DataToNextDel
		    deallocate Cursor_CW_DataToNextDel




	end




------





--------取得接转当前会计期间的数据并复制到临时表中 end ------------------------------------

--写结转信息
  If @@error = 0
  begin
     commit transaction CWDataToNext
   set @IsSuccess=1
  end
  else
  begin
    rollback transaction CWDataToNext
   set @IsSuccess=0
    raiserror('结转失败 ', 1, 20) 
  end








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG






















--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[CW_Data_START] (
                              @START_YYYYMM   varchar(20),   --传入当前会计期间
                              @START_YYYYMMDD  DATETIME,   --传入当前时间
                              @IsSuccess         int output     ---返回成功  -- 0 不成功  --1 
                            )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
Begin transaction CW_Start
   declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月
   declare  @SQLSTR         varchar(8000)  -- 下一个会计年月


declare @YYYYMM varchar(6)                   --会计年月     
declare @Current_YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。


declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)

declare @bill_type int           ---单据类型
declare @Detailflag int           ---单据类型
declare @YYYYMMBILL int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @VENDORID varchar(15)               --明细存货编号
declare @ItemBM varchar(20)               --明细存货编号
declare @NewItemBM varchar(20)               --明细存货编号
declare @PrevNO varchar(20)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,2)                          --数量
declare @PRICE  NUMERIC(20,2)               --含税单价
declare @Bqty NUMERIC(20,2)                          --数量
declare @BAMOUNT NUMERIC(20,2)                          --数量
declare @SumBAMOUNT NUMERIC(20,2)                          --数量
declare @EAMOUNT NUMERIC(20,2)                          --数量
declare @SumEAMOUNT NUMERIC(20,2)                          --数量
declare @BEGINAMOUNT NUMERIC(20,2)                          --数量
declare @balance NUMERIC(20,2)                          --数量
declare @Debit NUMERIC(20,2)                          --数量
declare @Credit NUMERIC(20,2)                          --数量
declare @SumDebit NUMERIC(20,2)                          --数量
declare @SumCredit NUMERIC(20,2)                          --数量

declare @BATCHCODE varchar(30)                     --序列号
declare @VALIDDATE DATEtime



declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BANKID VARCHAR(25)
declare @BILLDATE DATEtime
declare @B_ID INTEGER
declare @CW_STATUS INTEGER
declare @BenYueLastDay  VARCHAR(10)
  


	        set @YYYYMM    = @START_YYYYMM
         	SET @CW_STATUS =(select   ISNULL(CW_STATUS,0)   FROM  ACCINFO  WHERE GUID='0001')
---            set @YYYYMM   = (select optionvalue from accoptions where optionname ='CW_YYYYMM')       

            IF  @CW_STATUS=1                      ----已经启用帐套
             BEGIN
	     commit transaction CW_Start  

	   	   set @IsSuccess=1
	             RETURN
             END

--判断当前会计期间是否月结，不能重复月结


------为已经做凭证做准备

------删除当前启用帐套会计期间的月结记录

     Select @BenYueLastDay =CONVERT(varchar(100), dateadd(dd,-1,dateadd(m,1,Substring(@YYYYMM,1,4)+'-'+Substring(@YYYYMM,5,2)+'-01')), 23)

--------------其实会计科目初始化里面全部为明细科目

    delete  CW_BILLFLOW where YYYYMM = @YYYYMM and (YYYYMMBILL in (0,2,3))

    declare Cur_CLIENT_100 Cursor for Select   ItemBM,ISNULL(Debit,0) as Debit, ISNULL(Credit,0) as Credit ,ISNULL(balance,0) as balance  from CW_initbala   order by  ItemBM

    Open Cur_CLIENT_100

    fetch Cur_CLIENT_100 into    @ItemBM,@Debit, @Credit,@balance
    while @@fetch_status = 0            ----开始
    begin


		    set @NewItemBM=@ItemBM
			
		    select @PrevNO='9999AAAA'

		
	      while  (@PrevNO<>'0000') 
	      begin
	        select @Detailflag=Detailflag from ItemInfo where ItemBM=@NewItemBM


	            IF not exists(select *  from CW_BILLFLOW  where 
             		                                    (rtrim(ItemBM) = @NewItemBM)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 )       
	            BEGIN
                     execute  GETKEYVALUE     'CW_BillFlow',@R_KeyValue = @NEWID output
		    insert into CW_BillFlow 
		    (ID,YYYYMM,YYYYMMBILL,ItemBM,
		     BAMOUNT,debit,credit,EAMOUNT,Detailflag,brief,BILLDATE,Xuhao)
		    Values
		    (@NEWID,@YYYYMM,0,@NewItemBM,@balance,0,0,@balance,@Detailflag,'本期合计',@BenYueLastDay,'88888888')  
	            END     
		    else
		    begin	


--                       rawdebit = ( select isnull(sum(rawdebit),0) from  #CW_INITBALA_all 
--                                    where ItemBM like a.ItemBM +'%') ,
--			select SumBAMOUNT=isnull(sum(BAMOUNT),0),SumAMOUNT=isnull(sum(EAMOUNT),0), from  CW_BILLFLOW where ItemBM like @NewItemBM +'%'  and (rtrim(YYYYMMBILL) = 0) 

			update CW_BILLFLOW   set  BAMOUNT=( select isnull(sum(BAMOUNT),0) from  CW_BILLFLOW
                                    where ItemBM like @NewItemBM +'%'  and(rtrim(YYYYMMBILL) = 0) and Detailflag=1 ) ,
						  EAMOUNT=( select isnull(sum(EAMOUNT),0) from  CW_BILLFLOW
                                    where ItemBM like @NewItemBM +'%'  and(rtrim(YYYYMMBILL) = 0) and Detailflag=1 ) 					  						       
							 where 
             		                                    (rtrim(ItemBM) = @NewItemBM)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)

		    end			 ------IF   END

---	1、	yyyymmBill=0 ,本期起初、本期期末、本期收入合计、本期支出合计、

---	2、	yyyymmBill=2 ,本年起初、本年期末、本年收入累计、本期支出累计、

---     以上每个月都有一条

---     3、     yyyymmBill=3 ,本年收入累计、本期支出累计，启用帐套的记录，会计科目初始化的本年累计借方与贷方
------------------------------------------------------------------------------
	            IF not exists(select *  from CW_BILLFLOW  where 
             		                                    (rtrim(ItemBM) = @NewItemBM)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 2)       ---2代表本年合计记录
             		                                 )       
	            BEGIN
                     execute  GETKEYVALUE     'CW_BillFlow',@R_KeyValue = @NEWID output
		    insert into CW_BillFlow 
		    (ID,YYYYMM,YYYYMMBILL,ItemBM,
		     BAMOUNT,debit,credit,EAMOUNT,Detailflag,brief,BILLDATE,Xuhao)
		    Values
		    (@NEWID,@YYYYMM,2,@NewItemBM,@balance,@Debit,@Credit,0,@Detailflag,'本年累计',@BenYueLastDay,'99999999')  
	            END     
		    begin	
			update CW_BILLFLOW   set   Debit=( select isnull(sum(Debit),0) from  CW_BILLFLOW
                                    where ItemBM like @NewItemBM +'%'  and(rtrim(YYYYMMBILL) = 0) and Detailflag=1 ) , 					  						       
						  Credit=( select isnull(sum(Credit),0) from  CW_BILLFLOW
                                    where ItemBM like @NewItemBM +'%'  and(rtrim(YYYYMMBILL) = 0) and Detailflag=1 ),
						  BAMOUNT=( select isnull(sum(BAMOUNT),0) from  CW_BILLFLOW
                                   where ItemBM like @NewItemBM +'%'  and(rtrim(YYYYMMBILL) = 0) and Detailflag=1 ) 
						  where 
             		                                    (rtrim(ItemBM) = @NewItemBM)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 2)

		    end			 ------IF   END


------------------------

	            IF not exists(select *  from CW_BILLFLOW  where 
             		                                    (rtrim(ItemBM) = @NewItemBM)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 3)       ---2代表本年合计记录
             		                                 )       
	            BEGIN
                     execute  GETKEYVALUE     'CW_BillFlow',@R_KeyValue = @NEWID output
		    insert into CW_BillFlow 
		    (ID,YYYYMM,YYYYMMBILL,ItemBM,
		     BAMOUNT,debit,credit,EAMOUNT,Detailflag,brief,BILLDATE)
		    Values
		    (@NEWID,@YYYYMM,3,@NewItemBM,0,@Debit,@Credit,0,@Detailflag,'会计科目初始化本年累计',@BenYueLastDay)  
	            END     
		    begin	
			update CW_BILLFLOW   set  Debit=( select isnull(sum(Debit),0) from  CW_BILLFLOW
                                    where ItemBM like @NewItemBM +'%'  and(rtrim(YYYYMMBILL) = 0) and Detailflag=1 ) , 					  						       
						  Credit=( select isnull(sum(Credit),0) from  CW_BILLFLOW
                                    where ItemBM like @NewItemBM +'%'  and(rtrim(YYYYMMBILL) = 0) and Detailflag=1 ) 					  						       

						        where  (rtrim(ItemBM) = @NewItemBM)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 3)

		    end			 ------IF   END




------------------------

	        select @PrevNO=PrevNO from ItemInfo where ItemBM=@NewItemBM


		SET @NewItemBM=@PrevNO

	     end          -------while  @PrevNO<>'0000' 

	    fetch Cur_CLIENT_100 into    @ItemBM,@Debit, @Credit,@balance
       END


	    close Cur_CLIENT_100
	    deallocate Cur_CLIENT_100


----------------------------------------------------------------------------------

  update   accoptionS  set optionvalue = @START_YYYYMM          where optionname ='CW_YYYYMM'
  update   ACCINFO     set CW_STARTDATE= @START_YYYYMMDD , CW_STATUS= 1, CW_STARTYYYYMM= @START_YYYYMM         where GUID ='0001'
     



--------取得接转当前会计期间的数据并复制到临时表中 end ------------------------------------



--写结转信息
  If @@error = 0
  begin
     commit transaction CW_Start
   set @IsSuccess=1
  end
  else
  begin
    rollback transaction CW_Start
   set @IsSuccess=0
    raiserror('结转失败 ', 1, 20) 
  end
















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG








--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[CW_Data_START_DEL] (
		              @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                              @IsSuccess         int output     ---返回成功  -- 0 不成功  --1 
                            )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
Begin transaction CWDataToNext_DEL
   declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月
   declare  @SQLSTR         varchar(8000)  -- 下一个会计年月


declare @YYYYMM varchar(6)                   --会计年月     
declare @Current_YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。


declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)


declare  @STATUS INTEGER
  


         	SET @STATUS =(select   ISNULL(CW_STATUS,0)   FROM  ACCINFO  WHERE GUID='0001')

            IF  @STATUS=0        ----帐套未启用
             BEGIN
		  commit transaction CWDataToNext_DEL         
	   	  set @IsSuccess=1
	          RETURN
             END


-----------检测是否有凭证登帐    

        if exists(Select * from CW_PingZhengM where flagpost=1)	        
	begin
		set @RETURNSTRING ='已经有凭证登帐，不能反启用帐套！'
	     commit transaction CWDataToNext_DEL         
	   	   set @IsSuccess=0
	             RETURN

	end

	delete CW_BILLFLOW

----------------------------------------------------------------------------------

  update   accoptionS  set optionvalue = ''                         where optionname ='CW_YYYYMM'
  update   ACCINFO     set CW_STARTDATE= NULL,CW_STATUS= 0,CW_STARTYYYYMM= NULL          where GUID ='0001'
     



--------取得接转当前会计期间的数据并复制到临时表中 end ------------------------------------



--写结转信息
  If @@error = 0
  begin
     commit transaction CWDataToNext_DEL
   set @IsSuccess=1
  end
  else
  begin
    rollback transaction CWDataToNext_DEL
   set @IsSuccess=0
    raiserror('反启用帐套 ', 1, 20) 
  end














----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG















CREATE PROCEDURE [dbo].[CW_DengZhang]  
                 (
                  @BILLPost varchar(20)
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION

AS 
 
declare @BILLID  varchar(60)
declare @YYYYMM  varchar(10)
declare @INAMOUNT  NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @SUMBAMOUNT NUMERIC(20,10)            ---本期期初总金额
declare     @RETURNSTRINGXX    varchar(60)   
declare     @flagreturnXX int 
 
BEGIN

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='CW_YYYYMM')     

----------------------------------------------------------------

	    delete   CW_PingZhengD    where (ItemBM IS NULL  OR Len(ItemBM) <2 ) and  ( ISNULL(debit,0) =0  or  ISNULL(Credit,0)=0) 

------------登帐之前判断新增加的会计科目


--	    Select ItemBM from CW_PingZhengD where (BILLID IN (Select BILLID from CW_PingZhengM   where rtrim(YYYYMM) = @YYYYMM))
--						AND (ItemBM NOT IN (Select ITemBM From CW_BILLFLOW where YYYYMM = @YYYYMM and YYYYMMBILL=0))


------------------------------现金流数据准备
			update CW_PingZhengM set   CashMustFlag = 1
			where BILLID In (Select BILLID  From CW_PingZhengD  Where ItemBM In   (Select ItemBM  From ItemInfo Where XJLL=1))
------------------------------现金流数据准备

			

	    declare CW_DengZhang_Cursor Cursor for Select BILLID from CW_PingZhengM   where rtrim(YYYYMM) = @YYYYMM and FlagCheck=1
            		      ORDER BY BILLDATE

	    Open CW_DengZhang_Cursor

	    fetch CW_DengZhang_Cursor into @BILLID


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin


---		exec STORE_CW_PingZheng '00000002',@RETURNSTRINGXX,@flagreturnXX
		exec STORE_CW_PingZheng  @BILLID,@BILLPost,@RETURNSTRINGXX,@flagreturnXX

------------------------------现金流数据准备
			update CW_PingZhengM   set  CashDebit=( select isnull(sum(Debit),0) from  CW_PingZhengD
                                    where ItemBM In   (Select ItemBM  From ItemInfo Where XJLL=1) and BILLID=@BILLID ) ,
				  CashCredit=( select isnull(sum(Credit),0) from  CW_PingZhengD
                                    where ItemBM In   (Select ItemBM  From ItemInfo Where XJLL=1) and BILLID=@BILLID ) 					  						       
			where BILLID=@BILLID

------------------------------现金流数据准备
-------------------------------


---		print	@BILLID
---		print	@RETURNSTRINGXX
---		print	@flagreturnXX

		---select @RETURNSTRINGXX
		---select @flagreturnXX 

		    fetch CW_DengZhang_Cursor into @BILLID
 
	    END           ------- CW_DengZhang_Cursor  WHILE

	    close CW_DengZhang_Cursor
	    deallocate CW_DengZhang_Cursor

-----------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------现金流数据准备
			update CW_PingZhengM set   CashMustFlag = 0
			where CashDebit=CashCredit
------------------------------删除数据现金自身流转的
------------------------------现金流数据准备
		update CW_BILLFLOW set JHD= b.JHD  from CW_BILLFLOW a , iteminfo b where a.Itembm=b.Itembm
-------------------------------------------------------------------

END




----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











CREATE PROCEDURE [dbo].[CW_DengZhang_DEL]  
AS 
 
declare @BILLID  varchar(60)
declare @INAMOUNT  NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @SUMBAMOUNT NUMERIC(20,10)            ---本期期初总金额
declare @RETURNSTRINGXX    varchar(60)   
declare @flagreturnXX int 
declare @YYYYMM  varchar(10)

 
BEGIN

----------------------------------------------------------------
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='CW_YYYYMM')     

	    declare CW_DengZhang_DEL_Cursor Cursor for Select BILLID from CW_PingZhengM   where rtrim(YYYYMM) = @YYYYMM and FlagPost=1
            		      ORDER BY BILLDATE

	    Open CW_DengZhang_DEL_Cursor

	    fetch CW_DengZhang_DEL_Cursor into @BILLID


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin


---		exec STORE_CW_PingZheng_DEL '00000002',@RETURNSTRINGXX,@flagreturnXX
		exec STORE_CW_PingZheng_DEL @BILLID,@RETURNSTRINGXX,@flagreturnXX

		---select @RETURNSTRINGXX
		---select @flagreturnXX 

		    fetch CW_DengZhang_DEL_Cursor into @BILLID
 
	    END           ------- CW_DengZhang_DEL_Cursor  WHILE

	    close CW_DengZhang_DEL_Cursor
	    deallocate CW_DengZhang_DEL_Cursor

-----------------------------------------------------------------------------------------------------------------------------------------------------------


END



----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












------------------

CREATE PROCEDURE [dbo].[CW_GET_ItemInfo_ItemBM] (
                  @PrevNO varchar(50),
                  @bill_no_selfd varchar(50) output, --单号
		  @NextItemBMLen  INt  output
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --当前会计年月     
declare @idd varchar(50)
declare @HouBuidd varchar(50)                     --序列号
declare @BILLNOFLAG  varchar(1)                     --单据格式
declare @BILLW  varchar(20)                     --单据格式
declare @YYYYMM_FLAG  INTEGER
declare @Step0 int
declare @Step1 int
declare @Step2 int
declare @Step3 int
declare @Step4 int
declare @Step5 int
declare @Step6 int
declare @Step7 int
declare @Step8 int
declare @Step9 int

begin

---      select   @idd = (select max(substring(ItemBM,len(@PrevNO)+1,len(ItemBM)-len(@PrevNO))) as maxid from ItemInfo where PrevNO=@PrevNO)

	if @PrevNO='0000'
	begin
	      set  @bill_no_selfd =''
		return
	end

      select   @idd = (select max(ItemBM) as maxid from ItemInfo where PrevNO=@PrevNO)
--      select   @idd = (select max(substring(CODE,12,4)) as maxid from STOREZZHPM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
	set @HouBuIdd='1'+substring(@idd,len(@PrevNO)+1,len(@idd)-len(@PrevNO))

      set      @HouBuIdd = rtrim(convert(char,convert(int,@HouBuIdd)+1))
		
      set      @bill_no_selfd =substring(@HouBuidd,2,len(@HouBuidd)-1)



	select @Step0=Step0,@Step1=Step1,@Step2=Step2,@Step3=Step3,@Step4=Step4,@Step5=Step5,@Step6=Step6,@Step7=Step7,
		@Step8=Step8,@Step9=Step9  FROM  ACCINFO  WHERE GUID='0001'


            IF   Len(@PrevNO)=@Step0 
	    begin
		SET @NextItemBMLen=@Step1 
	    end

            IF   Len(@PrevNO)=@Step0+@Step1  
	    begin
		SET @NextItemBMLen=@Step2 
	    end
            IF   Len(@PrevNO)=@Step0+@Step1+@Step2   
	    begin
		SET @NextItemBMLen=@Step3 
	    end
            IF   Len(@PrevNO)=@Step0+@Step1+@Step2+@Step3
	    begin
		SET @NextItemBMLen=@Step4 
	    end

            IF   Len(@PrevNO)=@Step0+@Step1+@Step2+@Step3+@Step4
	    begin
		SET @NextItemBMLen=@Step5 
	    end
            IF   Len(@PrevNO)=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5
	    begin
		SET @NextItemBMLen=@Step6 
	    end
            IF   Len(@PrevNO)=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6
	    begin
		SET @NextItemBMLen=@Step7 
	    end
            IF   Len(@PrevNO)=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7
	    begin
		SET @NextItemBMLen=@Step8 
	    end
            IF   Len(@PrevNO)=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7+@Step8
	    begin
		SET @NextItemBMLen=@Step9 
	    end





end






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












----------------------------------------------------------------------------
CREATE PROCEDURE [CW_GET_Next_Item_len]  (  @PrevNO varchar(30),      ---单据编号   
	     @NextItemBMLen  INt  output)     --APSOFTENCRYPTION       WITH ENCRYPTION
AS 


declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @STOREHSFS   INTEGER
declare @MAXID   varchar(30)
declare @Step0 int
declare @Step1 int
declare @Step2 int
declare @Step3 int
declare @Step4 int
declare @Step5 int
declare @Step6 int
declare @Step7 int
declare @Step8 int
declare @Step9 int
 
BEGIN

	select @Step0=Step0,@Step1=Step1,@Step2=Step2,@Step3=Step3,@Step4=Step4,@Step5=Step5,@Step6=Step6,@Step7=Step7,
		@Step8=Step8,@Step9=Step9  FROM  ACCINFO  WHERE GUID='0001'


            IF   Len(@PrevNO)=@Step0  and @PrevNO<>'0000'
	    begin
		SET @NextItemBMLen=@Step1 
	    end
	    else
	    begin
		SET @NextItemBMLen=@Step0 
	    end

	    
            IF   Len(@PrevNO)=@Step0+@Step1  
	    begin
		SET @NextItemBMLen=@Step2 
	    end
            IF   Len(@PrevNO)=@Step0+@Step1+@Step2   
	    begin
		SET @NextItemBMLen=@Step3 
	    end
            IF   Len(@PrevNO)=@Step0+@Step1+@Step2+@Step3
	    begin
		SET @NextItemBMLen=@Step4 
	    end

            IF   Len(@PrevNO)=@Step0+@Step1+@Step2+@Step3+@Step4
	    begin
		SET @NextItemBMLen=@Step5 
	    end
            IF   Len(@PrevNO)=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5
	    begin
		SET @NextItemBMLen=@Step6 
	    end
            IF   Len(@PrevNO)=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6
	    begin
		SET @NextItemBMLen=@Step7 
	    end
            IF   Len(@PrevNO)=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7
	    begin
		SET @NextItemBMLen=@Step8 
	    end
            IF   Len(@PrevNO)=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7+@Step8
	    begin
		SET @NextItemBMLen=@Step9 
	    end


END
  







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG









CREATE PROCEDURE [dbo].[CW_GET_SUM] (@TableName  varchar(50),
				@BILLID  varchar(50),
				@GongShiStr  varchar(200),
				@ReturnAMT numeric(20, 2)  output)
AS 
  declare    @SqlSTR  varchar(1000)
  declare    @XX  varchar(1000)
  declare    @GongShiReturn  numeric(20, 2)
  declare    @SumAMT  numeric(20, 2)
   declare  @BeginMM int
   declare  @EndMM int
   declare  @MM int

BEGIN

 
Create Table #TempValue
      (   ABCD    varchar(50)  NULL
		)


	   Set  @BeginMM =Cast(SubString(@GongShiSTR,2,CHARINDEX(':',@GongShiSTR)-2) as INT)
	   set  @EndMM =Cast(SubString(@GongShiSTR,CHARINDEX(':',@GongShiSTR)+2,Len(@GongShiSTR)-CHARINDEX(':',@GongShiSTR)-1) as INT)


	   set  @MM=@BeginMM
		set @SumAMT=0

 		while  @MM<=@EndMM
		begin

			SET @SqlSTR=' delete  #TempValue  '
			exec (@SqlSTR)

			SET @SqlSTR=' INSERT  #TempValue  '
			SET @SqlSTR=@SqlSTR+' Select '+ SubString(@GongShiSTR,1,1)+' from '+@TableName+' where XuHao ='+Cast(@MM as Varchar(3))+' AND BILLID = '+@BILLID		

			exec (@SqlSTR)
				update #TempValue set ABCD=REPLACE(ABCD,',','')
				update #TempValue set ABCD=NULL  where Rtrim(Ltrim(ABCD))=''

				Select @XX=ABCD from  #TempValue


				Select @GongShiReturn=ISNULL(ABCD,0) from  #TempValue

				set @SumAMT=@SumAMT+ISNULL(@GongShiReturn,0)

		    set @MM=@MM+1

		end

	    set @ReturnAMT=@SumAMT


END




----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG















----   公式解析函数
----   2013.08.16

----   =ASC("SY,5101,本期贷方累计")-ASC("SY,5101,本期借方累计")

----   公式字符串示例  ASC("5101,201303,本期借方累计")

----   首先要解析字符串

----   需要定义函数来解决

----   解析   比如： C1+C2+D3+D4+D5+D6


CREATE PROCEDURE [dbo].[CW_GongShiZhiXing] (@TableName  varchar(50),@BILLID  varchar(50),@GongShiStr  varchar(2000),@YearMonth  varchar(10),@ReturnSTR varchar(100)  output)
AS 


BEGIN
   declare    @YYYYMM  varchar(6)
   declare    @MM  INT
   declare    @NN  INT
   declare    @KK  INT
   declare    @I  INT
   declare    @JJ  INT     ---------公式序数
   declare    @TempStr  varchar(2000)
   declare    @xx  varchar(2000)
   declare    @PrevFuHao  varchar(1)
   declare    @TempGongShi  varchar(200)
   declare    @SqlSTR  varchar(1000)
   declare    @ACCTCanShu  varchar(200)
   declare    @TempAMT money
   declare    @GongShiReturn  numeric(20, 2)



----   select  CHARINDEX(',','SY,5101,本期借方累计')
----   公式字符串示例  ASC("5101,201303,本期借方累计")
----   公式字符串示例  ACCT(5101,201308,本期借方累计)-ACCT(5101,201308,本期借方累计)+C2+D3
----   运算符合不支持（）
----   运算符合仅支持 + - * /


Create Table #TempGongshiValue
      (   ABCD    varchar(50)  NULL
		)




	  SET  @TempStr=@GongShiStr

	  Set @I=1
	  Set @JJ=1
	  Set @TempGongShi=''
	  Set @TempAMT=0
          set @PrevFuHao='B'  -----没有运算符号的时候
-----------第一个运算符的位置
----'ACCT(5101,201308,本期借方累计)'
  

	 while  @I < =Len(@TempStr)
	 begin
		If (SubString(@TempStr,@I,1) In ('+','-','*','/')) ---- OR (@I =Len(@TempStr))
		begin
------------------------计算
------------------------这个地方判断是什么公式
------------------------假如公式取得值  @GongShiReturn
------------------------首先判断是否ACCT 即判断公式性质
------------------------判断是否第一个函数
------------------------暂时不支持第一个为-负号
----ACCT(5101,本期贷方累计)-ACCT(5101,本期借方累计)

			Set  @MM= CHARINDEX('ACCT',@TempGongShi)
			IF @MM>0 
			begin
			  Set @ACCTCanShu=SuBstring(@TempGongShi,6,Len(@TempGongShi)-6)   ----示例  5101,201308,本期借方累计
			   
			  select @GongShiReturn=DBO.ACCT(@ACCTCanShu,@YearMonth)

			end

			Set  @NN= CHARINDEX('SUM',@TempGongShi)        
			IF @NN>0 
			begin
			  Set @ACCTCanShu=SuBstring(@TempGongShi,5,Len(@TempGongShi)-5)   ----示例  5101,201308,本期借方累计

				Print @TempGongShi
			   
			  exec CW_GET_SUM @TableName,@BILLID,@ACCTCanShu,@GongShiReturn  output

			end



			Set  @KK= CHARINDEX('XJLL',@TempGongShi)               -----XJLL(10010,流入)
			IF @KK>0 
			begin
			  Set @ACCTCanShu=SuBstring(@TempGongShi,6,Len(@TempGongShi)-6)   ----示例  5101,201308,本期借方累计

				Print @TempGongShi
			   
			  select @GongShiReturn=DBO.XJLL(@ACCTCanShu,@YearMonth)
--				select @GongShiReturn=11

			end




-----------------------  SubString(@TempGongShi,1,1)
			IF (SubString(@TempGongShi,1,1) IN ('A','B','C','D','E','F','G','H','I','J','K','L','M','N')) AND @MM=0 AND @NN=0 AND @KK=0
			begin
			
				SET @SqlSTR=' delete  #TempGongshiValue  '
				exec (@SqlSTR)

				SET @SqlSTR=' INSERT #TempGongshiValue  '
				SET @SqlSTR=@SqlSTR+' Select '+ SubString(@TempGongShi,1,1)+' from '+@TableName+' where XuHao='+SubString(@TempGongShi,2,len(@TempGongShi)-1)+' AND BILLID = '+@BILLID		
				exec (@SqlSTR)
					update #TempGongshiValue set ABCD=REPLACE(ABCD,',','')
					update #TempGongshiValue set ABCD=NULL  where Rtrim(Ltrim(ABCD))=''


--				Select @XX=ABCD from  #TempGongshiValue

--					print @xx
				Select @GongShiReturn=ISNULL(ABCD,0) from  #TempGongshiValue

			end
				if @GongShiReturn iS NULL
				Select @GongShiReturn=0

			
------------------------取本表的单元格-----需要用表明传递参数

------------------------记住前一运算负号
------------------------写一个二次嵌套
			if @JJ<>1
			begin
				if  @PrevFuHao='+' 
				begin
				Set @TempAMT=@TempAMT+@GongShiReturn
				end
				if  @PrevFuHao='-' 
				begin
				Set @TempAMT=@TempAMT-@GongShiReturn
				end
				if  @PrevFuHao='*' 
				begin
				Set @TempAMT=@TempAMT*@GongShiReturn
				end
				if  @PrevFuHao='/' 
				begin
				Set @TempAMT=@TempAMT/@GongShiReturn
				end

			end
			else
			begin
			       set @TempAMT=@GongShiReturn
			       set @JJ=@JJ+1
			end
		        set @PrevFuHao=SubString(@TempStr,@I,1)

			SET @TempGongShi=''
	
		end
		else
		begin
		  Set @TempGongShi=@TempGongShi+SubString(@TempStr,@I,1)
		end
	  Set @I=@I+1
	 end 
---------------------------------------------------
---------------------------------------------------
		if @I =Len(@TempStr)+1  ----符号后最后一个
		begin


			Set  @MM= CHARINDEX('ACCT',@TempGongShi)
			IF @MM>0 
			begin
			  Set @ACCTCanShu=SuBstring(@TempGongShi,6,Len(@TempGongShi)-6)   ----示例  5101,201308,本期借方累计
			   
			  select @GongShiReturn=DBO.ACCT(@ACCTCanShu,@YearMonth)

			end

			Set  @NN= CHARINDEX('SUM',@TempGongShi)              
			IF @NN>0 
			begin
				Print cast(@NN as varchar(10))
			  Set @ACCTCanShu=Substring(@TempGongShi,5,Len(@TempGongShi)-5)   ----示例  5101,201308,本期借方累计
				Print @TempGongShi
			   
			  exec CW_GET_SUM @TableName,@BILLID,@ACCTCanShu,@GongShiReturn  output

			end

			Set  @KK= CHARINDEX('XJLL',@TempGongShi)               -----XJLL(10010,流入)
			IF @KK>0 
			begin
			  Set @ACCTCanShu=SuBstring(@TempGongShi,6,Len(@TempGongShi)-6)   ----示例  5101,201308,本期借方累计

				Print @TempGongShi
			   
			  select @GongShiReturn=DBO.XJLL(@ACCTCanShu,@YearMonth)
--				select @GongShiReturn=11

			end





			IF (SubString(@TempGongShi,1,1) IN ('A','B','C','D','E','F','G','H','I','J','K','L','M','N')) AND @MM=0 AND @NN=0 AND @KK=0
			begin
			
				SET @SqlSTR=' delete  #TempGongshiValue  '
				exec (@SqlSTR)

				SET @SqlSTR=' INSERT #TempGongshiValue  '
				SET @SqlSTR=@SqlSTR+' Select '+ SubString(@TempGongShi,1,1)+' from '+@TableName+' where XuHao='+SubString(@TempGongShi,2,len(@TempGongShi)-1)+' AND BILLID = '+@BILLID				
--				print @SqlSTR
				exec (@SqlSTR)
					update #TempGongshiValue set ABCD=REPLACE(ABCD,',','')
					update #TempGongshiValue set ABCD=NULL  where Rtrim(Ltrim(ABCD))=''


--				Select @XX=ABCD from  #TempGongshiValue

--					print @xx
				Select @GongShiReturn=ISNULL(ABCD,0) from  #TempGongshiValue

			end
			
				if @GongShiReturn iS NULL
				Select @GongShiReturn=0




				if  @PrevFuHao='+' 
				begin
				Set @TempAMT=@TempAMT+@GongShiReturn
				end
				if  @PrevFuHao='-' 
				begin
				Set @TempAMT=@TempAMT-@GongShiReturn
				end
				if  @PrevFuHao='*' 
				begin
				Set @TempAMT=@TempAMT*@GongShiReturn
				end
				if  @PrevFuHao='/' 
				begin
				Set @TempAMT=@TempAMT/@GongShiReturn
				end
				if  @PrevFuHao='B'      --只有一个函数的时候
				begin
				Set @TempAMT=@GongShiReturn
				end
		end


--	Select @ReturnSTR = Cast(@TempAMT as varchar(100))  
	Select @ReturnSTR = CONVERT(varchar(100),@TempAMT,1)
		print @ReturnSTR


END










----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG
























--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE [dbo].[CW_INOUTMXB](@ItemBM varchar(30) ,                        -----如果为0000则全部仓库
                                                                                            @Begin_YYYYMM   varchar(10) ,
                                                                                           @End_YYYYMM   varchar(10) 
                        
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @End_YYYYMMAddone  datetime,
        @MAXBILLDATE  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
	@VENDOR_CLIENT_ID  varchar(20),
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8),
        @WHERESTING   varchar(1800)

declare @BANKNAME  varchar(50)
declare @ClientNAME  varchar(50)
declare @BANKSTR  varchar(50)
declare @STRZhaiYao   varchar(300)      -------收款方式、收款去向
declare @Memo   varchar(300)      -------收款方式、收款去向


declare @ID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare  @BILLTYPE  INTEGER
declare @BILLCODE  nvarchar(50)
declare @BILLDATE  datetime
declare @BILLTYPENAME  nvarchar(50)
declare @Begin_Date  varchar(10)
declare @Debit NUMERIC(20,10)
declare @Credit NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @EAMOUNTPREV NUMERIC(20,10)
---//==========
declare @BAMOUNT NUMERIC(20,10)
declare @MAXID  nvarchar(50)
declare @JHD  INT



                   set @now_date=(select   max(billDATE)   FROM CW_billflow)

		set @Begin_Date=substring(@Begin_YYYYMM,1,4)+'-'+substring(@Begin_YYYYMM,5,2)+'-01'

		update CW_BILLFLOW  set xuhao=ID  where xuhao is null   and  YYYYMMBILL=1
                       

                          SELECT    @WHERESTING  = '  AND     YYYYMM >='+char(39)+@Begin_YYYYMM+char(39)+' and  YYYYMM <='+char(39)+ @End_YYYYMM+char(39) 
                          SELECT    @BANKSTR  = '  AND     ItemBM ='+char(39)+@ItemBM+char(39)


     

Create Table #temptable1
      (ID  varchar(20) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
   YYYYMM  varchar(50)  NULL,
   xuhao  varchar(50)  NULL,
	[Debit] NUMERIC(20,10)  NULL ,
	[Credit] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
   zhaiyao  varchar(200)  NULL
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   ID , BILLID,BILLTYPE,BILLCODE,BILLDATE,BILLTYPE,YYYYMM,xuhao,  '
           SELECT  @SQLSTR = @SQLSTR+'Debit,Credit,EAMOUNT ,brief '
           SELECT  @SQLSTR = @SQLSTR+'  from CW_billflow   where yyyymmbill in (0,1,2)    '  + @WHERESTING+@BANKSTR 
           SELECT  @SQLSTR = @SQLSTR+'  order by id '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(20) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
   JHD int  NULL,
	[Debit] NUMERIC(20,10)  NULL ,
	[Credit] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
    zhaiyao nvarchar(300)  NULL,
    Memo nvarchar(300)  NULL,
		)


---------------------------------------------------
		select @JHD=JHD  from ItemInfo where ItemBM=@ItemBM

	          set @COUNTID='00000001'
	   if exists (Select  ID,BILLID,BILLTYPE, BILLCODE,BILLDATE,BILLTYPENAME,
                                                     isnull(Debit,0) as Debit ,  isnull(Credit,0) as Credit ,
                                                     isnull(EAMOUNT,0) as EAMOUNT   from  #temptable1        )
                 begin
	    declare INOUTMXBREP Cursor for Select  ID,BILLID,BILLTYPE , BILLCODE,BILLDATE,BILLTYPENAME,
                                                       isnull(Debit,0) as Debit ,   isnull(Credit,0) as Credit ,
                                                     isnull(EAMOUNT,0) as EAMOUNT ,zhaiyao  from  #temptable1         ORDER BY YYYYMM,BILLDATE,xuhao
	    Open INOUTMXBREP

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @Debit,@Credit,@EAMOUNT,@STRZhaiYao

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                        SELECT  @MAXID=ID  FROM CW_billflow  WHERE  ItemBM=@ItemBM  AND YYYYMM=@Begin_YYYYMM   AND YYYYMMBILL=0
                        IF @MAXID IS NULL
 			BEGIN
			SET  @BAMOUNT=0
			END
                        ELSE
			BEGIN
	                           SELECT @BAMOUNT=BAMOUNT   FROM   CW_billflow  WHERE ID=@MAXID
			END
                                                              
                          INSERT    INTO   #temptable2  (ID,BILLDATE, zhaiyao,EAMOUNT,JHD)
                                           VALUES  (@COUNTID ,@Begin_Date, '期初余额',@BAMOUNT,@JHD)
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
                       SELECT  @BILLTYPENAME=NAME FROM  BILLNAME  WHERE @BILLTYPENAME=BILLTYPEID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID


                    INSERT    INTO   #temptable2  (ID,BILLID,BILLTYPE, BILLCODE,BILLDATE,BILLTYPENAME,
                                                               Debit,Credit,EAMOUNT,zhaiyao,Memo,JHD)
                                           VALUES  (@COUNTID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @Debit,@Credit,@EAMOUNT,@STRZhaiYao,@Memo,@JHD)

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @Debit,@Credit,@EAMOUNT,@STRZhaiYao
 

	    END           ------- INOUTMXBREP  WHILE
	    close INOUTMXBREP
	    deallocate INOUTMXBREP
        end     ------------  if exists
---------------------------
---------解决当前仓库本期间未发生业务的货品
--                  delete    #temptable1
            ELSE
            BEGIN

                        SELECT  @ID=ID  FROM CW_billflow  WHERE  ItemBM=@ItemBM  AND YYYYMM=@Begin_YYYYMM   AND YYYYMMBILL=0

	             	  SELECT    @ID=ID,@EAMOUNT=BAMOUNT    FROM  CW_billflow  WHERE    ID = @ID   


                 SELECT  @BANKNAME= FullName   FROM ItemInfo  WHERE ItemBM=@ItemBM
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME         )
                                           VALUES  (@COUNTID,@BANKNAME)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                                                              
                          INSERT    INTO   #temptable2  (ID ,billdate, zhaiyao,EAMOUNT)
                                           VALUES  (@COUNTID,@Begin_Date,'期初余额',@EAMOUNT)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期末结存',@EAMOUNT)

---------------------------
	END




--------------------------

 SELECT *  FROM #temptable2         ORDER BY ID















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[CW_JieZhuanSY]  
                 (
		  @JieZhuanFlag  int ,    ----------- 1  
		  @DengZhangFlag  int ,    ----------- 0 不登帐  1登帐
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 

----损益科目结转金额始终以正数表示     @JieZhuanFlag=1
----损益科目结转方向与会计科目中定义的余额方向相反   @JieZhuanFlag=2

declare @YYYYMM varchar(6)                   --会计年月     
declare  @INF_COSTINGTYPEID  INT
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @BenNianLRKeMu  varchar(30) 
declare @CLIENTID varchar(10)                   --单句会计年月     
declare @ITEMNO varchar(15)               --明细存货编号
declare @ITEMNO00 varchar(15)               --明细存货编号
declare @ItemBM varchar(30)               --明细存货编号
declare @XuHao varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @MM   INT          --明细存货编号
declare @JHD   INT          --明细存货编号
declare @A   varchar(500)               --明细存货编号
declare @B   varchar(500)               --明细存货编号
declare @C   varchar(500)               --明细存货编号
declare @D   varchar(500)               --明细存货编号
declare @E   varchar(500)               --明细存货编号
declare @YearMonth  varchar(6)
declare @BILLTYPE   INTEGER
declare @SFLAG   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @EAMOUNT NUMERIC(20,2)
declare @Debit NUMERIC(20,2)
declare @Credit NUMERIC(20,2)
declare @BILLID_1 varchar(20)                   --单句会计年月     
declare @BILLID_2 varchar(20)                   --单句会计年月     
declare @CredTypeID int
declare @CredCode  int
declare @CredNO  int


                                              SET @RETURNSTRING='   '



     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CW_JieZhuanSY   --事物开始


-----------先检测凭证是否全部记账

	     set @YYYYMM   = (select optionvalue from accoptions where optionname ='CW_YYYYMM')     

	 if  exists(Select * from CW_PingZhengM where YYYYMM= @YYYYMM AND ISNULL(FlagPost,0)=0)

	  begin
		      rollback transaction trans_CW_JieZhuanSY
		      set  @flagreturn = 0
	              SET  @RETURNSTRING='本会计期间有未登帐的凭证，不能进行结转损益！'

	  end

-----@BenNianLRKeMu='3131'
	select @BenNianLRKeMu=BenNianLRKeMu  FROM  ACCINFO  WHERE GUID='0001'


----------如果正数或负数

----------同时生成两张单据，保存相反的方向

----------先生成两张空单据，一个是本年利润是借方，一个是本年利润为贷方

----------记住这两个的单据的ID那样能解决问题，


	     execute  GET_CWPZ_BILLID  @BILLID_1 output
	     set @BILLDATE= CONVERT(varchar(100), dateadd(day,-1,dateadd(Month,1,Cast(substring(@YYYYMM,1,4)+'-'+Substring(@YYYYMM,5,2)+'-01' as datetime))), 23)
-------------本月最后一天
	     SET @CredTypeID=1

             exec GET_Cred_Code_NO 1 ,@CredNo output,@CredCode output

            INSERT  INTO CW_PingZhengM (BILLID,YYYYMM,MAKEMAN,BILLDATE,CredTypeID,CredNo,CredCode,FlagCheck,BILLCheck)
		    VALUES (@BILLID_1,@YYYYMM,'机制',@BILLDATE,@CredTypeID,@CredNo,@CredCode,1,'机制')

            execute  GETKEYVALUE   'CW_PingZhengD',@R_KeyValue = @ITEMNO00 output


            INSERT  INTO CW_PingZhengD (BILLID,ITEMNO,ItemBM,Brief,debit,Credit)
		    VALUES (@BILLID_1,@ITEMNO00,@BenNianLRKeMu,'结转本期损益',0,0)

------------第一张单据，本年利润为借方
---------------以上是生成第一张单据


	     execute  GET_CWPZ_BILLID  @BILLID_2 output


             exec GET_Cred_Code_NO 1 ,@CredNo output,@CredCode output


            INSERT  INTO CW_PingZhengM (BILLID,YYYYMM,MAKEMAN,BILLDATE,CredTypeID,CredNo,CredCode,FlagCheck,BILLCheck)
		    VALUES (@BILLID_2,@YYYYMM,'机制',@BILLDATE,@CredTypeID,@CredNo,@CredCode,1,'机制')

            execute  GETKEYVALUE   'CW_PingZhengD',@R_KeyValue = @ITEMNO00 output


            INSERT  INTO CW_PingZhengD (BILLID,ITEMNO,ItemBM,Brief,debit,Credit)
		    VALUES (@BILLID_2,@ITEMNO00,@BenNianLRKeMu,'结转本期损益',0,0)


-----------------------

    declare Cursor_CW_JiezhanSY Cursor for Select ItemBM,JHD,EAMOUNT from CW_BILLFLOW where DetailFlag=1 and YYYYMMBILL=0 AND YYYYMM=@YYYYMM
				AND  Itembm Like '5%'  AND JHD=1  and ISNULL(Eamount,0)<>0
				Order By Itembm
    Open Cursor_CW_JiezhanSY

    fetch Cursor_CW_JiezhanSY into @ItemBM,@JHD,@EAMOUNT

    while @@fetch_status = 0            ----开始
    begin

            execute  GETKEYVALUE   'CW_PingZhengD',@R_KeyValue = @ITEMNO00 output

	    IF @JieZhuanFlag=1
	    begin
		    IF @EAMOUNT>0
		    begin
	        	    INSERT  INTO CW_PingZhengD (BILLID,ITEMNO,ItemBM,Brief,debit,Credit)
			    VALUES (@BILLID_1,@ITEMNO00,@ItemBM,'结转本期损益',0,@EAMOUNT)
		    end
		    IF @EAMOUNT<0
		    begin
		            INSERT  INTO CW_PingZhengD (BILLID,ITEMNO,ItemBM,Brief,debit,Credit)
			    VALUES (@BILLID_2,@ITEMNO00,@ItemBM,'结转本期损益',abs(@EAMOUNT),0)
		    end
	    end

	    IF @JieZhuanFlag=2
	    begin
        	    INSERT  INTO CW_PingZhengD (BILLID,ITEMNO,ItemBM,Brief,debit,Credit)
		    VALUES (@BILLID_1,@ITEMNO00,@ItemBM,'结转本期损益',0,@EAMOUNT)
	    end


    fetch Cursor_CW_JiezhanSY into @ItemBM,@JHD,@EAMOUNT

    END           ------- Cursor_CW_JiezhanSY  WHILE

    close Cursor_CW_JiezhanSY
    deallocate Cursor_CW_JiezhanSY
--------------------------------------结转损益类科目借方余额，损益科目结转金额始终以正数表示
    declare Cursor_CW_SY Cursor for Select ItemBM,JHD,EAMOUNT from CW_BILLFLOW where DetailFlag=1 and YYYYMMBILL=0 AND YYYYMM=@YYYYMM
				AND  Itembm Like '5%'  AND JHD=-1  and ISNULL(Eamount,0)<>0
				Order By Itembm
    Open Cursor_CW_SY

    fetch Cursor_CW_SY into @ItemBM,@JHD,@EAMOUNT

    while @@fetch_status = 0            ----开始
    begin

            execute  GETKEYVALUE   'CW_PingZhengD',@R_KeyValue = @ITEMNO00 output
	    IF @JieZhuanFlag=1
	    begin
		    IF @EAMOUNT>0
		    begin
        	    INSERT  INTO CW_PingZhengD (BILLID,ITEMNO,ItemBM,Brief,debit,Credit)
			    VALUES (@BILLID_2,@ITEMNO00,@ItemBM,'结转本期损益',@EAMOUNT,0)
		    end
		    IF @EAMOUNT<0
		    begin
        	    INSERT  INTO CW_PingZhengD (BILLID,ITEMNO,ItemBM,Brief,debit,Credit)
			    VALUES (@BILLID_1,@ITEMNO00,@ItemBM,'结转本期损益',0,abs(@EAMOUNT))
		    end
	    end
	    IF @JieZhuanFlag=2
	    begin
        	    INSERT  INTO CW_PingZhengD (BILLID,ITEMNO,ItemBM,Brief,debit,Credit)
			    VALUES (@BILLID_2,@ITEMNO00,@ItemBM,'结转本期损益',@EAMOUNT,0)
	    end

    fetch Cursor_CW_SY into @ItemBM,@JHD,@EAMOUNT

    END           ------- Cursor_CW_SY  WHILE

    close Cursor_CW_SY
    deallocate Cursor_CW_SY
--------------------------------------结转损益类科目贷方余额，损益科目结转金额始终以正数表示
	select @debit=sum(Credit) from CW_PingZhengD where BILLID=@BILLID_1
	select @Credit=sum(debit) from CW_PingZhengD where BILLID=@BILLID_2

	update CW_PingZhengD set debit=@debit  where BILLID=@BILLID_1  and itemBM=@BenNianLRKeMu
	update CW_PingZhengD set Credit=@Credit  where BILLID=@BILLID_2   and itemBM=@BenNianLRKeMu
---------解决已经结转还结转的操作
---------或者在程序顶部检测是否已经结转
	delete  CW_PingZhengM where BILLID IN (select BILLID from CW_PingZhengD where itemBM=@BenNianLRKeMu and ISNULL(debit,0) =0  and ISNULL(credit,0)=0 )

--------------
        IF @DengZhangFlag=1
	begin
	  exec CW_DengZhang  '机制'
	end

------------------------------------以上是删除全部单据明细

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CW_JieZhuanSY
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CW_JieZhuanSY
      set @flagreturn = 0
   end







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG









--------------------------------------------------------------------
CREATE PROCEDURE [dbo].[CW_KeMuYuEHZB](@BeginItemBM varchar(30) ,                        -----如果为0000则全部仓库
					    @ENDItemBM varchar(30) ,                        -----如果为0000则全部仓库
                                                                                            @Begin_YYYYMM   varchar(10) ,
                                                                                           @End_YYYYMM   varchar(10), 
                        				            @KeMuJiBie  int		

                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @End_YYYYMMAddone  datetime,
        @MAXBILLDATE  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
	@VENDOR_CLIENT_ID  varchar(20),
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8),
        @WHERESTING   varchar(1800)

declare @BANKNAME  varchar(50)
declare @ClientNAME  varchar(50)
declare @BANKSTR  varchar(500)
declare @STRZhaiYao   varchar(300)      -------收款方式、收款去向
declare @Memo   varchar(300)      -------收款方式、收款去向
declare @KeMuLenSTR  varchar(500)


declare @ID  varchar(50)
declare @BILLID  varchar(50)
declare @BILLTYPE  INTEGER
declare @NewYYYYMM  varchar(50)
declare @YYYYMM    varchar(50)
declare @BILLCODE  varchar(50)
declare @ItemBM    varchar(50)
declare @ItemBM00  varchar(50)
declare @BILLDATE  datetime
declare @Begin_Date  varchar(10)
declare @Debit NUMERIC(20,2)
declare @Credit NUMERIC(20,2)
declare @EAMOUNT NUMERIC(20,2)
declare @EAMOUNTPREV NUMERIC(20,2)
---//==========
declare @BAMOUNT NUMERIC(20,2)
declare @MAXID  varchar(50)
declare @KeMuLen  INT

declare @Step0 int
declare @Step1 int
declare @Step2 int
declare @Step3 int
declare @Step4 int
declare @Step5 int
declare @Step6 int
declare @Step7 int
declare @Step8 int
declare @Step9 int



                   set @now_date=(select   max(billDATE)   FROM CW_billflow)

		set @Begin_Date=substring(@Begin_YYYYMM,1,4)+'-'+substring(@Begin_YYYYMM,5,2)+'-01'

		update CW_BILLFLOW set jhd=b.jhd from CW_BILLFLOW a ,ItemInfo b where a.itembm=b.itembm

----------------第二个会计期间新增会计科目问题

----------------关于年中新增会计科目，增加新增会计科目的月结记录



                          SELECT    @BANKSTR  = '  AND     I.ItemBM >='+char(39)+@BeginItemBM+char(39)+'  AND  I.ItemBM <='+char(39)+@ENDItemBM+char(39)

                          SELECT    @WHERESTING  = '  AND     YYYYMM >='+char(39)+@Begin_YYYYMM+char(39)+' and  YYYYMM <='+char(39)+ @End_YYYYMM+char(39) 


	select @Step0=Step0,@Step1=Step1,@Step2=Step2,@Step3=Step3,@Step4=Step4,@Step5=Step5,@Step6=Step6,@Step7=Step7,
		@Step8=Step8,@Step9=Step9  FROM  ACCINFO  WHERE GUID='0001'



	IF @KeMuJiBie=1
	begin
		set @KeMuLen=@Step0
	end
	IF @KeMuJiBie=2
	begin
		set @KeMuLen=@Step0+@Step1
	end
	IF @KeMuJiBie=3
	begin
		set @KeMuLen=@Step0+@Step1+@Step2
	end
	IF @KeMuJiBie=4
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3
	end
	IF @KeMuJiBie=5
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4
	end
	IF @KeMuJiBie=6
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5
	end
	IF @KeMuJiBie=7
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6
	end
	IF @KeMuJiBie=8
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7
	end
	IF @KeMuJiBie=9
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7+@Step8
	end
	IF @KeMuJiBie=10
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7+@Step8+@Step9
	end


	SET @KeMuLenSTR	=' AND Len(I.ItemBM) <=  '+ Cast(@KeMuLen as Varchar(2))



     
---------------------------------------------------
		SELECT @SQLSTR='	select I.ITemBM,ISNULL(I.bamount,0)*I.JHD as bamount,E.Debit,E.Credit,(ISNULL(I.bamount,0)+(ISNULL(E.Debit,0)-ISNULL(E.Credit,0))*I.JHD)*I.JHD as Eamount,X.Debit as LeiJiDebit,X.Credit as LeiJiCredit  from  CW_BILLFLOW '
		SELECT @SQLSTR=@SQLSTR+'	 as I '
		SELECT @SQLSTR=@SQLSTR+'	 left outer join '
		SELECT @SQLSTR=@SQLSTR+'	 (select ITemBM,isnull(sum(Debit),0) as Debit ,isnull(sum(Credit),0) as Credit from  CW_BILLFLOW where  YYYYMMBILL=1 '+@WHERESTING
		SELECT @SQLSTR=@SQLSTR+'		Group BY ITemBM 	'
		SELECT @SQLSTR=@SQLSTR+'	 ) as E ON E.ITemBM=I.ITemBM '
		SELECT @SQLSTR=@SQLSTR+'	 left outer join  '
		SELECT @SQLSTR=@SQLSTR+'	 (select ITemBM,isnull(Debit,0) as Debit ,isnull(Credit,0) as Credit from  CW_BILLFLOW where  YYYYMMBILL=2 ' +'and  YYYYMM ='+char(39)+ @End_YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+'	 ) as X ON X.ITemBM=I.ITemBM '
		SELECT @SQLSTR=@SQLSTR+'	where yyyymmbill=0   AND     YYYYMM = '+char(39)+@Begin_YYYYMM+char(39)+@BANKSTR +@KeMuLenSTR	
		SELECT @SQLSTR=@SQLSTR+'	 Order by I.ITemBM '
------------------------------------------------------------------------
		EXEC(@SQLSTR)
















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











CREATE PROCEDURE [dbo].[CW_LRBMB_CRAET_CW_LRB](@BILLID varchar(8),                        -----如果为0000则全部仓库
						           @YearMonth   varchar(10),  
								   @RETURNSTRING    varchar(60)    output      ---单据编号   
                                                      )    --APSOFTENCRYPTION       WITH ENCRYPTION
as
declare @CODE00   [varchar] (25)   
declare @NewBILLID   varchar (50)   
declare @SFLAG  INTEGER
declare @BILLTYPE   INTEGER
declare @NewBILLDATE DATEtime


-------利润表的模板是唯一的，所以不需要传递参数  @BILLID

-----	select @BILLID = BILLID from STORECW_LRBMBM


	EXEC CW_BILL_XuHao_ChongPai 'STORECW_LRBMBD',@BILLID

	delete STORECW_LRBM  WHERE YearMonth=@YearMonth

----------如果存在就删除
	
	INSERT INTO STORECW_LRBM
	SELECT *  FROM  STORECW_LRBMBM WHERE BILLID=@BILLID

	INSERT INTO STORECW_LRBD
	SELECT *  FROM  STORECW_LRBMBD WHERE BILLID=@BILLID


	UPDATE STORECW_LRBM SET CODE=Substring(@YearMonth,1,4)+'年'+Substring(@YearMonth,5,2)+'月',
				YearMonth=@YearMonth,BillDate=getdate() WHERE BILLID=@BILLID


	UPDATE STORECW_LRBM SET BILLID=@YearMonth+BILLID   WHERE BILLID=@BILLID 
	UPDATE STORECW_LRBD SET ItemNO=@YearMonth+ItemNO   WHERE BILLID=@YearMonth+@BILLID


	SET @NewBILLID=@YearMonth+@BILLID
	declare @RETURNSTRING00  varchar(60) 
	declare @flagreturn00 int    ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
	exec CW_LRB_JiSuan  @NewBILLID,@RETURNSTRING00 ,@flagreturn00 output  

--	select @flagreturn




	SET @RETURNSTRING ='成功生成报表，表号为'+ @YearMonth















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG









----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[CW_LRB_JiSuan]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare  @INF_COSTINGTYPEID  INT
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @CLIENTID varchar(10)                   --单句会计年月     
declare @ITEMNO varchar(15)               --明细存货编号
declare @XuHao varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @MM   INT          --明细存货编号
declare @A   varchar(500)               --明细存货编号
declare @B   varchar(500)               --明细存货编号
declare @C   varchar(500)               --明细存货编号
declare @D   varchar(500)               --明细存货编号
declare @E   varchar(500)               --明细存货编号
declare @YearMonth  varchar(6)
declare @BILLTYPE   INTEGER
declare @SFLAG   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @C_GongShi   varchar(500)               --明细存货编号
declare @D_GongShi   varchar(500)               --明细存货编号
declare @E_GongShi   varchar(500)               --明细存货编号
declare @C_Value   varchar(500)               --明细存货编号
declare @D_Value   varchar(500)               --明细存货编号
declare @E_Value   varchar(500)               --明细存货编号


                                              SET @RETURNSTRING='   '


	set @BILLID   = ltrim(rtrim(@BILLID))
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CW_LRB_DEL   --事物开始

     set @YearMonth =   (select YearMonth  from STORECW_LRBM where rtrim(BILLID) = @BILLID)


    declare SM_Consign_CW_LRB_DEL Cursor for Select ITEMNO,XuHao,A,B ,C,D,E   from STORECW_LRBD where rtrim(BILLID) = @BILLID  Order BY ITEMNO

    Open SM_Consign_CW_LRB_DEL

    fetch SM_Consign_CW_LRB_DEL into @ITEMNO,@XuHao,@A,@B,@C,@D,@E

    while @@fetch_status = 0            ----开始
    begin

--------------分别取C列与D列公式

		
		select @C_GongShi=C From STORECW_LRBMBD where XuHao=@XuHao

		select @D_GongShi=D From STORECW_LRBMBD where XuHao=@XuHao

		select @E_GongShi=E From STORECW_LRBMBD where XuHao=@XuHao



--     select PATINDEX('%[0-9]%', '234GHJ')
--     select PATINDEX('%[A-Fa-f]%', '234GHJ')
-----------------需要判断是否需要计算，是否是公式

			IF	CHARINDEX('ACCT',@C_GongShi)>0  OR 
				(PATINDEX('%[A-Na-n]%', @C_GongShi) >0 and PATINDEX('%[0-9]%', @C_GongShi) >0)
			begin
		                exec [dbo].[CW_GongShiZhiXing] 'STORECW_LRBD',@BILLID,@C_GongShi,@YearMonth, @C_Value output
			end
			else
			begin
		                SET @C_Value=@C_GongShi
			end
	
----------------------------------------------------			
			IF	CHARINDEX('ACCT',@D_GongShi)>0  OR 
				(PATINDEX('%[A-Na-n]%', @D_GongShi) >0 and PATINDEX('%[0-9]%', @D_GongShi) >0)
			begin
		                exec [dbo].[CW_GongShiZhiXing] 'STORECW_LRBD',@BILLID,@D_GongShi,@YearMonth, @D_Value output
			end
			else
			begin
		                SET @D_Value=@D_GongShi
			end
------------------------------------------------------	
			IF	CHARINDEX('ACCT',@E_GongShi)>0  OR 
				(PATINDEX('%[A-Na-n]%', @E_GongShi) >0 and PATINDEX('%[0-9]%', @E_GongShi) >0)
			begin
		                exec [dbo].[CW_GongShiZhiXing] 'STORECW_LRBD',@BILLID,@E_GongShi,@YearMonth, @E_Value output
			end
			else
			begin
		                SET @E_Value=@E_GongShi
			end
-------------------------------------------------------	

		update STORECW_LRBD SET C=@C_Value,D=@D_Value,E=@E_Value    where ItemNO=@ITEMNO

		update STORECW_LRBD SET C=NULL    where C='0.00'
		update STORECW_LRBD SET D=NULL    where D='0.00'
		update STORECW_LRBD SET E=NULL    where E='0.00'


-----CREATE PROCEDURE [dbo].[CW_GongShiZhiXing] (@TableName  varchar(50),@GongShiStr  varchar(2000),@YearMonth  varchar(10),@ReturnSTR varchar(100)  output)


--------------------
    fetch SM_Consign_CW_LRB_DEL into @ITEMNO,@XuHao,@A,@B,@C,@D,@E

    END           ------- SM_Consign_CW_LRB_DEL  WHILE

    close SM_Consign_CW_LRB_DEL
    deallocate SM_Consign_CW_LRB_DEL


------------------------------------以上是删除全部单据明细

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CW_LRB_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CW_LRB_DEL
      set @flagreturn = 0
   end


----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG

























--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE [dbo].[CW_RJZINOUTMXB](@ItemBM varchar(30) ,                        -----如果为0000则全部仓库
                                                                                            @Begin_YYYYMM   varchar(10) ,
                                                                                           @End_YYYYMM   varchar(10) 
                        
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @End_YYYYMMAddone  datetime,
        @MAXBILLDATE  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
	@VENDOR_CLIENT_ID  varchar(20),
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8),
        @WHERESTING   varchar(1800)

declare @BANKNAME  varchar(50)
declare @ClientNAME  varchar(50)
declare @BANKSTR  varchar(50)
declare @STRZhaiYao   varchar(300)      -------收款方式、收款去向
declare @Memo   varchar(300)      -------收款方式、收款去向


declare @ID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare  @BILLTYPE  INTEGER
declare  @DuiFangKeMu  varchar(50)
declare @BILLCODE  nvarchar(50)
declare @BILLDATE  datetime
declare @BILLTYPENAME  nvarchar(50)
declare @Begin_Date  varchar(10)
declare @Debit NUMERIC(20,10)
declare @Credit NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @EAMOUNTPREV NUMERIC(20,10)
---//==========
declare @BAMOUNT NUMERIC(20,10)
declare @MAXID  nvarchar(50)
declare @JHD  INT


                   set @now_date=(select   max(billDATE)   FROM CW_billflow)

		set @Begin_Date=substring(@Begin_YYYYMM,1,4)+'-'+substring(@Begin_YYYYMM,5,2)+'-01'

		update CW_BILLFLOW  set xuhao=ID  where xuhao is null   and  YYYYMMBILL=1
                      

                          SELECT    @WHERESTING  = '  AND     YYYYMM >='+char(39)+@Begin_YYYYMM+char(39)+' and  YYYYMM <='+char(39)+ @End_YYYYMM+char(39) 
                          SELECT    @BANKSTR  = '  AND     ItemBM ='+char(39)+@ItemBM+char(39)


  


Create Table #temptable1
      (ID  varchar(20) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
   YYYYMM  varchar(50)  NULL,
   xuhao  varchar(50)  NULL,
	[Debit] NUMERIC(20,10)  NULL ,
	[Credit] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
   zhaiyao  varchar(200)  NULL,
   ItemBM  varchar(30)  NULL
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   ID , BILLID,BILLTYPE,BILLCODE,BILLDATE,BILLTYPE,YYYYMM, xuhao, '
           SELECT  @SQLSTR = @SQLSTR+'Debit,Credit,EAMOUNT ,brief,duifangkemu as ItemBM '
           SELECT  @SQLSTR = @SQLSTR+'  from CW_billflow   where yyyymmbill in (0,1,2)    '  + @WHERESTING+@BANKSTR 
           SELECT  @SQLSTR = @SQLSTR+'  order by id '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(20) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
   JHD_1 int  NULL,
	[Debit] NUMERIC(20,10)  NULL ,
	[Credit] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
    zhaiyao nvarchar(300)  NULL,
    Memo nvarchar(300)  NULL,
    ItemBM  varchar(30)  NULL
		)


---------------------------------------------------
		select @JHD=JHD  from ItemInfo where ItemBM=@ItemBM

	          set @COUNTID='00000001'
	   if exists (Select  ID,BILLID,BILLTYPE, BILLCODE,BILLDATE,BILLTYPENAME,
                                                     isnull(Debit,0) as Debit ,  isnull(Credit,0) as Credit ,
                                                     isnull(EAMOUNT,0) as EAMOUNT   from  #temptable1        )
                 begin
	    declare INOUTMXBREP Cursor for Select  ID,BILLID,BILLTYPE , BILLCODE,BILLDATE,BILLTYPENAME,
                                                       isnull(Debit,0) as Debit ,   isnull(Credit,0) as Credit ,
                                                     isnull(EAMOUNT,0) as EAMOUNT ,ItemBM,zhaiyao  from  #temptable1         ORDER BY YYYYMM,BILLDATE,xuhao
	    Open INOUTMXBREP

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @Debit,@Credit,@EAMOUNT,@DuiFangKemu,@STRZhaiYao

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                        SELECT  @MAXID=ID  FROM CW_billflow  WHERE  ItemBM=@ItemBM  AND YYYYMM=@Begin_YYYYMM   AND YYYYMMBILL=0
                        IF @MAXID IS NULL
 			BEGIN
			SET  @BAMOUNT=0
			END
                        ELSE
			BEGIN
	                           SELECT @BAMOUNT=BAMOUNT   FROM   CW_billflow  WHERE ID=@MAXID
			END
                                                              
                          INSERT    INTO   #temptable2  (ID,BILLDATE, zhaiyao,EAMOUNT,JHD_1)
                                           VALUES  (@COUNTID ,@Begin_Date, '期初余额',@BAMOUNT,@JHD)
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID


                    INSERT    INTO   #temptable2  (ID,BILLID,BILLTYPE, BILLCODE,BILLDATE,ItemBM,
                                                               Debit,Credit,EAMOUNT,zhaiyao,Memo,JHD_1)
                                           VALUES  (@COUNTID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@DuiFangKeMu,
                                                               @Debit,@Credit,@EAMOUNT,@STRZhaiYao,@Memo,@JHD)

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @Debit,@Credit,@EAMOUNT,@DuiFangKemu,@STRZhaiYao
 

	    END           ------- INOUTMXBREP  WHILE

	    close INOUTMXBREP
	    deallocate INOUTMXBREP
        end     ------------  if exists
---------------------------
---------解决当前仓库本期间未发生业务的货品
--                  delete    #temptable1
            ELSE
            BEGIN

                        SELECT  @ID=ID  FROM CW_billflow  WHERE  ItemBM=@ItemBM  AND YYYYMM=@Begin_YYYYMM   AND YYYYMMBILL=0

	             	  SELECT    @ID=ID,@EAMOUNT=BAMOUNT    FROM  CW_billflow  WHERE    ID = @ID   


                 SELECT  @BANKNAME= FullName   FROM ItemInfo  WHERE ItemBM=@ItemBM
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME         )
                                           VALUES  (@COUNTID,@BANKNAME)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                                                              
                          INSERT    INTO   #temptable2  (ID ,billdate, zhaiyao,EAMOUNT)
                                           VALUES  (@COUNTID,@Begin_Date,'期初余额',@EAMOUNT)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期末结存',@EAMOUNT)

---------------------------
	END




--------------------------

 SELECT *  FROM #temptable2         ORDER BY ID
















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG










--------------------------------------------------------------------
CREATE PROCEDURE [dbo].[CW_ShiSuanPHB](     @Begin_YYYYMM   varchar(10) ,
                                            @End_YYYYMM   varchar(10), 
                        				            @KeMuJiBie  int		

                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @End_YYYYMMAddone  datetime,
        @MAXBILLDATE  datetime,
        @temp_year   varchar(10), 
	@VENDOR_CLIENT_ID  varchar(20),
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8),
        @WHERESTING   varchar(1800)

declare @BANKNAME  varchar(50)
declare @ClientNAME  varchar(50)
declare @BANKSTR  varchar(50)
declare @STRZhaiYao   varchar(300)      -------收款方式、收款去向
declare @Memo   varchar(300)      -------收款方式、收款去向


declare @ID  varchar(50)
declare @BILLID  varchar(50)
declare @BILLTYPE  INTEGER
declare @NewYYYYMM  varchar(50)
declare @YYYYMM    varchar(50)
declare @BILLCODE  varchar(50)
declare @ItemBM    varchar(50)
declare @ItemBM00  varchar(50)
declare @BILLDATE  datetime
declare @Begin_Date  varchar(10)
declare @Debit NUMERIC(20,2)
declare @Credit NUMERIC(20,2)
declare @EAMOUNT NUMERIC(20,2)
declare @EAMOUNTPREV NUMERIC(20,2)
declare @KeMuLen  INT
declare @KeMuLenSTR  varchar(500)

declare @Step0 int
declare @Step1 int
declare @Step2 int
declare @Step3 int
declare @Step4 int
declare @Step5 int
declare @Step6 int
declare @Step7 int
declare @Step8 int
declare @Step9 int

---//==========
declare @BAMOUNT NUMERIC(20,2)
declare @MAXID  varchar(50)
  declare @bdebit_count numeric(20,6),
	  @bcredit_count numeric(20,6),
	  @debit_count numeric(20,6),
	  @credit_count numeric(20,6),
	  @edebit_count numeric(20,6),
	  @ecredit_count numeric(20,6),
          @ydebit_count numeric(20,6),
	  @ycredit_count numeric(20,6)




		set @Begin_Date=substring(@Begin_YYYYMM,1,4)+'-'+substring(@Begin_YYYYMM,5,2)+'-01'






	select @Step0=Step0,@Step1=Step1,@Step2=Step2,@Step3=Step3,@Step4=Step4,@Step5=Step5,@Step6=Step6,@Step7=Step7,
		@Step8=Step8,@Step9=Step9  FROM  ACCINFO  WHERE GUID='0001'



	IF @KeMuJiBie=1
	begin
		set @KeMuLen=@Step0
	end
	IF @KeMuJiBie=2
	begin
		set @KeMuLen=@Step0+@Step1
	end
	IF @KeMuJiBie=3
	begin
		set @KeMuLen=@Step0+@Step1+@Step2
	end
	IF @KeMuJiBie=4
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3
	end
	IF @KeMuJiBie=5
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4
	end
	IF @KeMuJiBie=6
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5
	end
	IF @KeMuJiBie=7
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6
	end
	IF @KeMuJiBie=8
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7
	end
	IF @KeMuJiBie=9
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7+@Step8
	end
	IF @KeMuJiBie=10
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7+@Step8+@Step9
	end


	SET @KeMuLenSTR	=' where  Len(I.ItemBM) <=  '+ Cast(@KeMuLen as Varchar(2))





----------------第二个会计期间新增会计科目问题

----------------关于年中新增会计科目，增加新增会计科目的月结记录

  create table #trytable (
    ItemBMBB    varchar(50)  NULL,
    ItemBM    varchar(50)  NULL,
    FullName    varchar(300)  NULL,
    debit  numeric(20,6) NULL,--本期借方
    credit numeric(20,6) NULL,--本期贷方
    ydebit numeric(20,6) NULL,--本年累计借方
    ycredit numeric(20,6) NULL,--本年累计贷方
    bdebit numeric(20,6) NULL,--期初借方
    bcredit numeric(20,6) NULL,--期初贷方
    edebit numeric(20,6) NULL,--期末借方
    ecredit numeric(20,6) NULL)--期末贷方
 



                          SELECT    @WHERESTING  = '  AND     YYYYMM >='+char(39)+@Begin_YYYYMM+char(39)+' and  YYYYMM <='+char(39)+ @End_YYYYMM+char(39) 

     
	        SELECT @SQLSTR = ' INSERT #trytable  '
		SELECT @SQLSTR=@SQLSTR+'	 select I.ITemBM as ItemBMBB ,I.ITemBM, I.FullName,  isnull(E.Debit,0) as Debit,isnull(E.Credit,0) as Credit,'
		SELECT @SQLSTR=@SQLSTR+'	 			   case when isnull(M.Debit,0)>isnull(M.Credit,0) then isnull(M.Debit,0)-isnull(M.Credit,0)'
		SELECT @SQLSTR=@SQLSTR+'	 			   else 0 '
		SELECT @SQLSTR=@SQLSTR+'	 			   end  as  YDebit,'
		SELECT @SQLSTR=@SQLSTR+'	 			   case when isnull(M.Credit,0)>isnull(M.Debit,0) then isnull(M.Credit,0)-isnull(M.Debit,0)'
		SELECT @SQLSTR=@SQLSTR+'	 			   else 0 '
		SELECT @SQLSTR=@SQLSTR+'	 			   end  as  YCredit,'
		SELECT @SQLSTR=@SQLSTR+'	 			   isnull(N.Bamount,0) as BDebit,isnull(X.Bamount,0) as BCredit,'
		SELECT @SQLSTR=@SQLSTR+'	 			   case when I.JHD=1 then  isnull(BB.Bamount,0)+isnull(E.Debit,0)-isnull(E.Credit,0)'
		SELECT @SQLSTR=@SQLSTR+'	 			   else 0 '
		SELECT @SQLSTR=@SQLSTR+'	 			   end  as  EDebit,'
		SELECT @SQLSTR=@SQLSTR+'	 			   case when I.JHD=-1 then  isnull(BB.Bamount,0)-isnull(E.Debit,0)+isnull(E.Credit,0)'
		SELECT @SQLSTR=@SQLSTR+'	 			   else 0 '
		SELECT @SQLSTR=@SQLSTR+'	 			   end  as  ECredit	'
		SELECT @SQLSTR=@SQLSTR+'	 	        From  ItemInfo  '
		SELECT @SQLSTR=@SQLSTR+'	 	  AS I '
		SELECT @SQLSTR=@SQLSTR+'	 	 left outer join '
		SELECT @SQLSTR=@SQLSTR+'	 	 (select ITemBM,isnull(sum(Debit),0) as Debit ,isnull(sum(Credit),0) as Credit from  CW_BILLFLOW where YYYYMMBILL=1 '+@WHERESTING
		SELECT @SQLSTR=@SQLSTR+'	 		Group BY ITemBM 	'
		SELECT @SQLSTR=@SQLSTR+'	 	 ) as E ON E.ITemBM=I.ITemBM '
		SELECT @SQLSTR=@SQLSTR+'	 	 left outer join '
		SELECT @SQLSTR=@SQLSTR+'	 	 (select ITemBM,isnull(Debit,0) as Debit,isnull(Credit,0) as Credit  from  CW_BILLFLOW where   YYYYMMBILL=2  and   YYYYMM = '+char(39)+ @End_YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+'	 	 ) as M ON M.ITemBM=I.ITemBM '
		SELECT @SQLSTR=@SQLSTR+'	 	 left outer join '
		SELECT @SQLSTR=@SQLSTR+'	 	 (select ITemBM,isnull(Bamount,0) as Bamount from  CW_BILLFLOW where JHD=1  and YYYYMMBILL=0   AND   YYYYMM ='+char(39)+@Begin_YYYYMM+char(39)
		SELECT @SQLSTR=@SQLSTR+'	 	 ) as N ON N.ITemBM=I.ITemBM '
		SELECT @SQLSTR=@SQLSTR+'	 	 left outer join '
		SELECT @SQLSTR=@SQLSTR+'	 	 (select ITemBM,isnull(Bamount,0) as Bamount from  CW_BILLFLOW where JHD=-1  and YYYYMMBILL=0   AND     YYYYMM ='+char(39)+@Begin_YYYYMM+char(39)
		SELECT @SQLSTR=@SQLSTR+'	 	 ) as X ON X.ITemBM=I.ITemBM '
		SELECT @SQLSTR=@SQLSTR+'	 	 left outer join '
		SELECT @SQLSTR=@SQLSTR+'	 	 (select ITemBM,isnull(Bamount,0) as Bamount from  CW_BILLFLOW where  YYYYMMBILL=0  and   YYYYMM ='+char(39)+@Begin_YYYYMM+char(39)
		SELECT @SQLSTR=@SQLSTR+'	 	 ) as BB ON BB.ITemBM=I.ITemBM '
---		SELECT @SQLSTR=@SQLSTR+'	 	where  len(I.ItemBM)=4 '
		SELECT @SQLSTR=@SQLSTR+@KeMuLenSTR

	            EXEC( @SQLSTR)


  update #trytable set ecredit = -edebit	  where edebit<0

  update #trytable set edebit = 0	  where edebit<0


  update #trytable set edebit = -ecredit	  where ecredit<0

  update #trytable set ecredit = 0	  where ecredit<0
--------------------

  update #trytable set Bcredit = -Bdebit	  where Bdebit<0

  update #trytable set Bdebit = 0	  where Bdebit<0


  update #trytable set Bdebit = -Bcredit	  where Bcredit<0

  update #trytable set Bcredit = 0	  where Bcredit<0
------------------------
  select @bdebit_count = sum(bdebit),
         @bcredit_count = sum(bcredit),
         @debit_count = sum(debit),
         @credit_count = sum(credit),
         @edebit_count = sum(edebit),
         @ecredit_count = sum(ecredit),
         @ydebit_count = sum(ydebit),
         @ycredit_count = sum(ycredit)
  from #trytable where len(ItemBM)=4 


  insert into #trytable (ItemBMBB,FullName, bdebit, bcredit, debit, credit, edebit, ecredit, ydebit, ycredit)
                         values('99999999999999999999',
                               '          合  计 ',@bdebit_count,@bcredit_count,@debit_count,@credit_count,
                                                @edebit_count,@ecredit_count,@ydebit_count,@ycredit_count)  

  delete from #trytable where     (bdebit=0 or bdebit is null)
                              and (bcredit=0 or bcredit is null)
                              and (debit=0 or debit is null)
                              and (credit=0 or credit is null)
                              and (edebit=0 or edebit is null)
                              and (ecredit=0 or ecredit is null)  

  select ItemBM,FullName, bdebit, bcredit, debit, credit, edebit, ecredit, ydebit, ycredit   
	  from #trytable  
	  order by ItemBMBB 
---  drop table #trytable

---	select *  from #trytable where  ItemBM='1001'











----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG

















CREATE                PROCEDURE CW_UpdateCW_INITBALAtotal
AS
  set nocount on

  DECLARE @Debit T_DOUBLE
  DECLARE @Credit T_DOUBLE
  DECLARE @Balance T_DOUBLE
  DECLARE @STEP0 SMALLINT


  create table #CW_INITBALA99 (ItemBM varchar(32),
                             fullname varchar(400),
                             step0 varchar(1),
                             moneyid integer  NULL ,  
                             rate numeric(38,8) ,      
                             rawdebit numeric(38,8) ,    ----年初借方       
                             rawcredit numeric(38,8) ,   ----年初贷方         
                             rawbalance numeric(38,8) ,   
                             debit numeric(38,8) ,         
                             credit numeric(38,8) ,         
                             balance numeric(38,8) ,         
                             balance_jie numeric(38,8) ,       ----期初借方  
                             balance_Dai numeric(38,8) ,       ----期初贷方    
                             plhavedone numeric(38,8),        
                             refreshflag varchar(1), 
			     [DCFlag] int  NULL )


  create table #CW_INITBALA_all ( ItemBM varchar(32),
                             fullname varchar(400),
                             step0 varchar(1),
                             moneyid integer  NULL ,  
                             rate numeric(38,8) NOT NULL ,      
                             rawdebit numeric(38,8) ,    ----年初借方       
                             rawcredit numeric(38,8) ,   ----年初贷方         
                             rawbalance numeric(38,8) NOT NULL ,   
                             debit numeric(38,8) NOT NULL ,         
                             credit numeric(38,8) NOT NULL ,         
                             balance numeric(38,8) NOT NULL ,         
                             balance_jie numeric(38,8) ,       ----期初借方  
                             balance_Dai numeric(38,8) ,       ----期初贷方    
                             plhavedone numeric(38,8) NOT NULL ,       
                             refreshflag varchar(1), 
			     [DCFlag] int  NULL )



  -- 求综合本位币的数据
-----现在只求一种货币的数据
/*  UPDATE CW_INITBALA
  SET
    Debit=Src.Debit,Credit=Src.Credit,Balance=Src.Balance,PLHaveDone=Src.PLHaveDone
    
  FROM(SELECT ItemBM,SUM(Debit) Debit,SUM(Credit) Credit,SUM(Balance) Balance,
    SUM(PLHaveDone) PLHaveDone
    FROM CW_INITBALA 
    WHERE MoneyID<>99 GROUP BY ItemBM
  ) Src
  WHERE CW_INITBALA.MoneyID=99 AND CW_INITBALA.ItemBM=Src.ItemBM
*/

-------在一种货币的情况下不需要以上指令

    --选入CW_INITBALA表中99数据到临时表
/*    insert into #CW_INITBALA_all select b.ItemBM,b.fullname,'F' as step0,  a.* from CW_INITBALA  a, ItemInfo b 
             where a.ItemBM = b.ItemBM and a.moneyid = 99
*/
    insert into #CW_INITBALA_all select b.ItemBM,b.fullname,'F' as step0,  a.moneyid,	a.rate,	a.rawdebit,	a.rawcredit,	a.rawbalance,	a.debit,	a.credit,a.balance, 0  as balance_jie, 0  as balance_Dai, a.plhavedone,	a.refreshflag,	a.DCFlag from CW_INITBALA  a, ItemInfo b 
             where a.ItemBM = b.ItemBM 



    update #CW_INITBALA_all set rawbalance = - a.rawbalance ,
                         balance = -a.balance  
          from #CW_INITBALA_all a , ItemInfo b 
          where a.ItemBM = b.ItemBM and b.dcflag <>1    -- 为了能向上级求合统计 将balance改为科目的方向无关  
   
    insert into #CW_INITBALA99 select * from #CW_INITBALA_all
    --插入非底层的科目
    insert into #CW_INITBALA99 (ItemBM,fullname,moneyid) 
       select a.ItemBM ,a.fullname, 99 as moneyid
           from ItemInfo a 
                where a.detailflag <> 1
    
/*    update #CW_INITBALA99 set rate = ( select isnull(max(rate),1)   from #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%' and moneyid = a.moneyid ) ,
                       rawdebit = ( select isnull(sum(rawdebit),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%' and moneyid = a.moneyid ) ,

                       rawcredit = ( select isnull(sum(rawcredit),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%' and moneyid = a.moneyid ) ,
               
                       rawbalance = ( select isnull(sum(rawbalance),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%' and moneyid = a.moneyid ) ,


                       debit = ( select isnull(sum(debit),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%' and moneyid = a.moneyid ) ,

                       credit = ( select isnull(sum(credit),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%' and moneyid = a.moneyid ) ,

                       balance = ( select isnull(sum(balance),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%' and moneyid = a.moneyid ) ,
 

                       plhavedone = ( select isnull(sum(plhavedone),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%' and moneyid = a.moneyid ) 
    from #CW_INITBALA99 a , ItemInfo b 
    where a.ItemBM = b.ItemBM and b.detailflag <> 1 

*/
    update #CW_INITBALA99 set rate = ( select isnull(max(rate),1)   from #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%') ,
                       rawdebit = ( select isnull(sum(rawdebit),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%') ,

                       rawcredit = ( select isnull(sum(rawcredit),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%') ,
               
                       rawbalance = ( select isnull(sum(rawbalance),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%' ) ,


                       debit = ( select isnull(sum(debit),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%') ,

                       credit = ( select isnull(sum(credit),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%') ,

                       balance = ( select isnull(sum(balance),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%') ,
 

                       plhavedone = ( select isnull(sum(plhavedone),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%') 
    from #CW_INITBALA99 a , ItemInfo b 
    where a.ItemBM = b.ItemBM and b.detailflag <> 1 


   
    --处理CW_INITBALA 的余额方向
    update #CW_INITBALA99 set rawbalance = - a.rawbalance , 
                        balance = -a.balance 
           from #CW_INITBALA99 a , ItemInfo b 
           where a.ItemBM = b.ItemBM and b.dcflag <>1 --and b.detailflag <> 1   

-----------和上边的处理余额方向相反，相对应     

---    FieldByName('YearBalance').AsFloat=FieldByName('Balance').AsFloat-FieldByName('Debit').AsFloat+FieldByName('credit').AsFloat;

-------处理年初余额

    update #CW_INITBALA99 set Rawbalance = Balance-Debit+credit from #CW_INITBALA99 

--                             rawdebit numeric(38,8) ,    ----年初借方       
--                             rawcredit numeric(38,8) ,   ----年初贷方         

    --处理#CW_INITBALA99 的期初借方、贷方，以及处理年初借方与贷方
    update #CW_INITBALA99 set balance_Dai = a.balance,rawcredit=a.Rawbalance 
           from #CW_INITBALA99 a , ItemInfo b 
           where a.ItemBM = b.ItemBM and b.dcflag <>1 --and b.detailflag <> 1   

    update #CW_INITBALA99 set balance_Jie = a.balance , rawdebit=a.Rawbalance
           from #CW_INITBALA99 a , ItemInfo b 
           where a.ItemBM = b.ItemBM and b.dcflag =1 --and b.detailflag <> 1   

-----------和上边的处理余额方向相反，相对应     

  
 SELECT @STEP0=STEP0 FROM ACCINFO
/*   IF (@STEP0=4)
    SELECT @Debit=sum(Debit),@Credit=sum(Credit),@balance = Sum(Case When dcflag =1 then Balance else -Balance end ) 
    FROM #CW_INITBALA99 a, ItemInfo s  WHERE a.MoneyID=99 and a.ItemBM = s.ItemBM 
    AND   a.ItemBM Like '____' 
  ELSE
   SELECT @Debit=sum(Debit),@Credit=sum(Credit),@balance = Sum(Case When dcflag =1 then Balance else -Balance end ) 
    FROM #CW_INITBALA99 a, ItemInfo s  WHERE a.MoneyID=99 and a.ItemBM = s.ItemBM 
    AND  a.ItemBM Like '___' 
*/

-------以上不知道是什么意思，暂时屏蔽掉

/*  INSERT INTO #CW_INITBALA99
    (ItemBM,ItemBM,fullname,MoneyID,
    Debit,Credit,Balance)
  VALUES(-99999,'99999999999999','合    计',-9999,
    ROUND(@Debit,2),ROUND(@Credit,2),@Balance)
*/
-------以上不知道是何用途，暂时屏蔽掉
-------step0  一级科目的标志

  update #CW_INITBALA99 set  step0 = 'T' where len(ItemBM) = @STEP0
  select ItemBM, fullname,step0,moneyid, rate, rawdebit, rawcredit, rawbalance, debit, credit,
		 balance, balance_jie, balance_dai, plhavedone, refreshflag
  from #CW_INITBALA99 order by ItemBM
  drop table #CW_INITBALA_all
  drop table #CW_INITBALA99












----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












CREATE PROCEDURE [dbo].[CW_XJLLBMB_CRAET_CW_XJLLB](@BILLID varchar(8),                        -----如果为0000则全部仓库
						           @YearMonth   varchar(10),  
								   @RETURNSTRING    varchar(60)    output      ---单据编号   
                                                      )    --APSOFTENCRYPTION       WITH ENCRYPTION
as
declare @CODE00   [varchar] (25)   
declare @NewBILLID   varchar (50)   
declare @SFLAG  INTEGER
declare @BILLTYPE   INTEGER
declare @NewBILLDATE DATEtime


-------利润表的模板是唯一的，所以不需要传递参数  @BILLID

-----	select @BILLID = BILLID from STORECW_XJLLBMBM


	EXEC CW_BILL_XuHao_ChongPai 'STORECW_XJLLBMBD',@BILLID

	delete STORECW_XJLLBM  WHERE YearMonth=@YearMonth

----------如果存在就删除
	
	INSERT INTO STORECW_XJLLBM
	SELECT *  FROM  STORECW_XJLLBMBM WHERE BILLID=@BILLID

	INSERT INTO STORECW_XJLLBD
	SELECT *  FROM  STORECW_XJLLBMBD WHERE BILLID=@BILLID


	UPDATE STORECW_XJLLBM SET CODE=Substring(@YearMonth,1,4)+'年'+Substring(@YearMonth,5,2)+'月',
				YearMonth=@YearMonth,BillDate=getdate() WHERE BILLID=@BILLID


	UPDATE STORECW_XJLLBM SET BILLID=@YearMonth+BILLID   WHERE BILLID=@BILLID 
	UPDATE STORECW_XJLLBD SET ItemNO=@YearMonth+ItemNO   WHERE BILLID=@YearMonth+@BILLID


	SET @NewBILLID=@YearMonth+@BILLID
	declare @RETURNSTRING00  varchar(60) 
	declare @flagreturn00 int    ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
	exec CW_XJLLB_JiSuan  @NewBILLID,@RETURNSTRING00 ,@flagreturn00 output  

--	select @flagreturn




	SET @RETURNSTRING ='成功生成报表，表号为'+ @YearMonth
















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG










----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[CW_XJLLB_JiSuan]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare  @INF_COSTINGTYPEID  INT
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @CLIENTID varchar(10)                   --单句会计年月     
declare @ITEMNO varchar(15)               --明细存货编号
declare @XuHao varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @MM   INT          --明细存货编号
declare @A   varchar(500)               --明细存货编号
declare @B   varchar(500)               --明细存货编号
declare @C   varchar(500)               --明细存货编号
declare @D   varchar(500)               --明细存货编号
declare @E   varchar(500)               --明细存货编号
declare @YearMonth  varchar(6)
declare @BILLTYPE   INTEGER
declare @SFLAG   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @C_GongShi   varchar(500)               --明细存货编号
declare @D_GongShi   varchar(500)               --明细存货编号
declare @E_GongShi   varchar(500)               --明细存货编号
declare @C_Value   varchar(500)               --明细存货编号
declare @D_Value   varchar(500)               --明细存货编号
declare @E_Value   varchar(500)               --明细存货编号


                                              SET @RETURNSTRING='   '


	set @BILLID   = ltrim(rtrim(@BILLID))
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CW_XJLLB_DEL   --事物开始

     set @YearMonth =   (select YearMonth  from STORECW_XJLLBM where rtrim(BILLID) = @BILLID)


    declare SM_Consign_CW_XJLLB_DEL Cursor for Select ITEMNO,XuHao,A,B ,C,D,E   from STORECW_XJLLBD where rtrim(BILLID) = @BILLID  Order BY ITEMNO

    Open SM_Consign_CW_XJLLB_DEL

    fetch SM_Consign_CW_XJLLB_DEL into @ITEMNO,@XuHao,@A,@B,@C,@D,@E

    while @@fetch_status = 0            ----开始
    begin

--------------分别取C列与D列公式

		
		select @C_GongShi=C From STORECW_XJLLBMBD where XuHao=@XuHao

		select @D_GongShi=D From STORECW_XJLLBMBD where XuHao=@XuHao




--     select PATINDEX('%[0-9]%', '234GHJ')
--     select PATINDEX('%[A-Fa-f]%', '234GHJ')
-----------------需要判断是否需要计算，是否是公式

			IF	CHARINDEX('ACCT',@C_GongShi)>0  OR 
				(PATINDEX('%[A-Na-n]%', @C_GongShi) >0 and PATINDEX('%[0-9]%', @C_GongShi) >0)
			begin
		                exec [dbo].[CW_GongShiZhiXing] 'STORECW_XJLLBD',@BILLID,@C_GongShi,@YearMonth, @C_Value output
			end
			else
			begin
		                SET @C_Value=@C_GongShi
			end
	
----------------------------------------------------			
			IF	CHARINDEX('ACCT',@D_GongShi)>0  OR 
				(PATINDEX('%[A-Na-n]%', @D_GongShi) >0 and PATINDEX('%[0-9]%', @D_GongShi) >0)
			begin
		                exec [dbo].[CW_GongShiZhiXing] 'STORECW_XJLLBD',@BILLID,@D_GongShi,@YearMonth, @D_Value output
			end
			else
			begin
		                SET @D_Value=@D_GongShi
			end
------------------------------------------------------	

		update STORECW_XJLLBD SET C=@C_Value,D=@D_Value   where ItemNO=@ITEMNO

		update STORECW_XJLLBD SET C=NULL    where C='0.00'
		update STORECW_XJLLBD SET D=NULL    where D='0.00'


-----CREATE PROCEDURE [dbo].[CW_GongShiZhiXing] (@TableName  varchar(50),@GongShiStr  varchar(2000),@YearMonth  varchar(10),@ReturnSTR varchar(100)  output)


--------------------
    fetch SM_Consign_CW_XJLLB_DEL into @ITEMNO,@XuHao,@A,@B,@C,@D,@E

    END           ------- SM_Consign_CW_XJLLB_DEL  WHILE

    close SM_Consign_CW_XJLLB_DEL
    deallocate SM_Consign_CW_XJLLB_DEL


------------------------------------以上是删除全部单据明细

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CW_XJLLB_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CW_XJLLB_DEL
      set @flagreturn = 0
   end



----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG







CREATE PROCEDURE [dbo].[CW_XianJinLLFP](@BILLID varchar(20),                        -----如果为0000则全部仓库
					   @RETURNSTRING    varchar(500)    output ,     ---单据编号   
			                   @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） 
                                                      )    --APSOFTENCRYPTION       WITH ENCRYPTION
as
declare @CODE00   [varchar] (25)   
declare @CashDebit NUMERIC(20,2)
declare @CashCredit NUMERIC(20,2)
declare @SumDebit NUMERIC(20,2)
declare @SumCredit NUMERIC(20,2)
declare @STR00   [varchar] (100)   
declare @STR11   [varchar] (100)   
declare @STR22   [varchar] (100)   

	select @SumDebit=Isnull(sum(Debit),0),@SumCredit=Isnull(sum(Credit),0)    from CW_CashItemTMP where BILLID=@BILLID

	select @CashDebit=Isnull(CashDebit,0),@CashCredit=Isnull(CashCredit,0)    from CW_PingZhengM where BILLID=@BILLID
	
	set @flagreturn=0

        set @STR00='凭证中现金流量类科目借方、贷方差额为：'+ cast((@CashDebit-@CashCredit) as Varchar(20))
        set @STR11='而现金流量金额分配中流入、流出差额为：'+ cast((@SumDebit-@SumCredit) as Varchar(20))
        set @STR22='两者不相等！分配不正确！'

	IF @SumDebit=@CashDebit and @SumCredit=@CashCredit
	BEGIN
	delete  CW_CashItem where BILLID=@BILLID

	INSERT INTO CW_CashItem
	SELECT *  FROM  CW_CashItemTMP WHERE BILLID=@BILLID and (ISNULL(Debit,0)<>0 OR ISNULL(Credit,0)<>0)

	update CW_PingZhengM  set CashFlag=1  where BILLID=@BILLID
	set @flagreturn=1

	SET @RETURNSTRING ='成功分配现金流量'
	END
        ELSE
	BEGIN
	set @flagreturn=0
	SET @RETURNSTRING =@STR00+@STR11+@STR22
	END







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












CREATE PROCEDURE [dbo].[CW_ZCFZBMB_CRAET_CW_ZCFZB](@BILLID varchar(8),                        -----如果为0000则全部仓库
						           @YearMonth   varchar(10),  
								   @RETURNSTRING    varchar(60)    output      ---单据编号   
                                                      )    --APSOFTENCRYPTION       WITH ENCRYPTION
as
declare @CODE00   [varchar] (25)   
declare @NewBILLID   varchar (50)   
declare @SFLAG  INTEGER
declare @BILLTYPE   INTEGER
declare @NewBILLDATE DATEtime


-------利润表的模板是唯一的，所以不需要传递参数  @BILLID

-----	select @BILLID = BILLID from STORECW_ZCFZBMBM


	EXEC CW_BILL_XuHao_ChongPai 'STORECW_ZCFZBMBD',@BILLID

	delete STORECW_ZCFZBM  WHERE YearMonth=@YearMonth

----------如果存在就删除
	
	INSERT INTO STORECW_ZCFZBM
	SELECT *  FROM  STORECW_ZCFZBMBM WHERE BILLID=@BILLID

	INSERT INTO STORECW_ZCFZBD
	SELECT *  FROM  STORECW_ZCFZBMBD WHERE BILLID=@BILLID


	UPDATE STORECW_ZCFZBM SET CODE=Substring(@YearMonth,1,4)+'年'+Substring(@YearMonth,5,2)+'月',
				YearMonth=@YearMonth,BillDate=getdate() WHERE BILLID=@BILLID


	UPDATE STORECW_ZCFZBM SET BILLID=@YearMonth+BILLID   WHERE BILLID=@BILLID 
	UPDATE STORECW_ZCFZBD SET ItemNO=@YearMonth+ItemNO   WHERE BILLID=@YearMonth+@BILLID


	SET @NewBILLID=@YearMonth+@BILLID
	declare @RETURNSTRING00  varchar(60) 
	declare @flagreturn00 int    ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
	exec CW_ZCFZB_JiSuan  @NewBILLID,@RETURNSTRING00 ,@flagreturn00 output  

--	select @flagreturn




	SET @RETURNSTRING ='成功生成报表，表号为'+ @YearMonth
















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[CW_ZCFZB_JiSuan]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare  @INF_COSTINGTYPEID  INT
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @CLIENTID varchar(10)                   --单句会计年月     
declare @ITEMNO varchar(15)               --明细存货编号
declare @XuHao varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @MM   INT          --明细存货编号
declare @A   varchar(500)               --明细存货编号
declare @B   varchar(500)               --明细存货编号
declare @C   varchar(500)               --明细存货编号
declare @D   varchar(500)               --明细存货编号
declare @E   varchar(500)               --明细存货编号
declare @F   varchar(500)               --明细存货编号
declare @G   varchar(500)               --明细存货编号
declare @H   varchar(500)               --明细存货编号
declare @YearMonth  varchar(6)
declare @BILLTYPE   INTEGER
declare @SFLAG   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @C_GongShi   varchar(500)               --明细存货编号
declare @D_GongShi   varchar(500)               --明细存货编号
declare @G_GongShi   varchar(500)               --明细存货编号
declare @H_GongShi   varchar(500)               --明细存货编号
declare @C_Value   varchar(500)               --明细存货编号
declare @D_Value   varchar(500)               --明细存货编号
declare @G_Value   varchar(500)               --明细存货编号
declare @H_Value   varchar(500)               --明细存货编号


                                              SET @RETURNSTRING='   '


	set @BILLID   = ltrim(rtrim(@BILLID))
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CW_ZCFZB_DEL   --事物开始

     set @YearMonth =   (select YearMonth  from STORECW_ZCFZBM where rtrim(BILLID) = @BILLID)


    declare SM_Consign_CW_ZCFZB_DEL Cursor for Select ITEMNO,XuHao,A,B ,C,D,E,F,G,H   from STORECW_ZCFZBD where rtrim(BILLID) = @BILLID  Order BY ITEMNO

    Open SM_Consign_CW_ZCFZB_DEL

    fetch SM_Consign_CW_ZCFZB_DEL into @ITEMNO,@XuHao,@A,@B,@C,@D,@E,@F,@G,@H

    while @@fetch_status = 0            ----开始
    begin

--------------分别取C列与D列公式

		
		select @C_GongShi=C From STORECW_ZCFZBMBD where XuHao=@XuHao

		select @D_GongShi=D From STORECW_ZCFZBMBD where XuHao=@XuHao

		select @G_GongShi=G From STORECW_ZCFZBMBD where XuHao=@XuHao

		select @H_GongShi=H From STORECW_ZCFZBMBD where XuHao=@XuHao

                           print  @xuhao



--     select PATINDEX('%[0-9]%', '234GHJ')
--     select PATINDEX('%[A-Fa-f]%', '234GHJ')
-----------------需要判断是否需要计算，是否是公式

			IF	CHARINDEX('ACCT',@C_GongShi)>0  OR 
				(PATINDEX('%[A-Na-n]%', @C_GongShi) >0 and PATINDEX('%[0-9]%', @C_GongShi) >0)
			begin
		                exec [dbo].[CW_GongShiZhiXing] 'STORECW_ZCFZBD',@BILLID,@C_GongShi,@YearMonth, @C_Value output
			end
			else
			begin
		                SET @C_Value=@C_GongShi
			end
	
----------------------------------------------------			
			IF	CHARINDEX('ACCT',@D_GongShi)>0  OR 
				(PATINDEX('%[A-Na-n]%', @D_GongShi) >0 and PATINDEX('%[0-9]%', @D_GongShi) >0)
			begin
		                exec [dbo].[CW_GongShiZhiXing] 'STORECW_ZCFZBD',@BILLID,@D_GongShi,@YearMonth, @D_Value output
			end
			else
			begin
		                SET @D_Value=@D_GongShi
			end
------------------------------------------------------	
			IF	CHARINDEX('ACCT',@G_GongShi)>0  OR 
				(PATINDEX('%[A-Na-n]%', @G_GongShi) >0 and PATINDEX('%[0-9]%', @G_GongShi) >0)
			begin
		                exec [dbo].[CW_GongShiZhiXing] 'STORECW_ZCFZBD',@BILLID,@G_GongShi,@YearMonth, @G_Value output
			end
			else
			begin
		                SET @G_Value=@G_GongShi
			end
-------------------------------------------------------	
			IF	CHARINDEX('ACCT',@H_GongShi)>0  OR 
				(PATINDEX('%[A-Na-n]%', @H_GongShi) >0 and PATINDEX('%[0-9]%', @H_GongShi) >0)
			begin
		                exec [dbo].[CW_GongShiZhiXing] 'STORECW_ZCFZBD',@BILLID,@H_GongShi,@YearMonth, @H_Value output
			end
			else
			begin
		                SET @H_Value=@H_GongShi
			end
-------------------------------------------------------	


		update STORECW_ZCFZBD SET C=@C_Value,D=@D_Value,G=@G_Value,H=@H_Value    where ItemNO=@ITEMNO

		update STORECW_ZCFZBD SET C=NULL    where C='0.00'
		update STORECW_ZCFZBD SET D=NULL    where D='0.00'
		update STORECW_ZCFZBD SET G=NULL    where G='0.00'
		update STORECW_ZCFZBD SET H=NULL    where H='0.00'


-----CREATE PROCEDURE [dbo].[CW_GongShiZhiXing] (@TableName  varchar(50),@GongShiStr  varchar(2000),@YearMonth  varchar(10),@ReturnSTR varchar(100)  output)


--------------------
    fetch SM_Consign_CW_ZCFZB_DEL into @ITEMNO,@XuHao,@A,@B,@C,@D,@E,@F,@G,@H

    END           ------- SM_Consign_CW_ZCFZB_DEL  WHILE

    close SM_Consign_CW_ZCFZB_DEL
    deallocate SM_Consign_CW_ZCFZB_DEL


------------------------------------以上是删除全部单据明细

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CW_ZCFZB_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CW_ZCFZB_DEL
      set @flagreturn = 0
   end



----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG























--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE [dbo].[CW_ZongFenLeiZhang](@BeginItemBM varchar(30) ,                        -----如果为0000则全部仓库
					    @ENDItemBM varchar(30) ,                        -----如果为0000则全部仓库
                                                                                            @Begin_YYYYMM   varchar(10) ,
                                                                                           @End_YYYYMM   varchar(10) ,
				            @KeMuJiBie  int		
                        
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @End_YYYYMMAddone  datetime,
        @MAXBILLDATE  datetime,
        @temp_year   varchar(10), 
	@VENDOR_CLIENT_ID  varchar(20),
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8),
        @WHERESTING   varchar(1800)

declare @BANKNAME  varchar(50)
declare @ClientNAME  varchar(50)
declare @BANKSTR  varchar(500)
declare @KeMuLenSTR  varchar(500)

declare @STRZhaiYao   varchar(300)      -------收款方式、收款去向
declare @Memo   varchar(300)      -------收款方式、收款去向


declare @ID  varchar(50)
declare @BILLID  varchar(50)
declare @BILLTYPE  INTEGER
declare @NewYYYYMM  varchar(50)
declare @YYYYMM    varchar(50)
declare @BILLCODE  varchar(50)
declare @ItemBM    varchar(50)
declare @ItemBM00  varchar(50)
declare @BILLDATE  datetime
declare @Begin_Date  varchar(10)
declare @Debit NUMERIC(20,2)
declare @Credit NUMERIC(20,2)
declare @EAMOUNT NUMERIC(20,2)
declare @EAMOUNTPREV NUMERIC(20,2)
---//==========
declare @BAMOUNT NUMERIC(20,2)
declare @MAXID  varchar(50)
declare @JHD  INT
declare @KeMuLen  INT

declare @Step0 int
declare @Step1 int
declare @Step2 int
declare @Step3 int
declare @Step4 int
declare @Step5 int
declare @Step6 int
declare @Step7 int
declare @Step8 int
declare @Step9 int





		set @Begin_Date=substring(@Begin_YYYYMM,1,4)+'-'+substring(@Begin_YYYYMM,5,2)+'-01'

                       

                          SELECT    @WHERESTING  = '  AND     YYYYMM >='+char(39)+@Begin_YYYYMM+char(39)+' and  YYYYMM <='+char(39)+ @End_YYYYMM+char(39) 
                          SELECT    @BANKSTR  = '  AND     ItemBM >='+char(39)+@BeginItemBM+char(39)+'  AND     ItemBM <='+char(39)+@ENDItemBM+char(39)



	select @Step0=Step0,@Step1=Step1,@Step2=Step2,@Step3=Step3,@Step4=Step4,@Step5=Step5,@Step6=Step6,@Step7=Step7,
		@Step8=Step8,@Step9=Step9  FROM  ACCINFO  WHERE GUID='0001'



	IF @KeMuJiBie=1
	begin
		set @KeMuLen=@Step0
	end
	IF @KeMuJiBie=2
	begin
		set @KeMuLen=@Step0+@Step1
	end
	IF @KeMuJiBie=3
	begin
		set @KeMuLen=@Step0+@Step1+@Step2
	end
	IF @KeMuJiBie=4
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3
	end
	IF @KeMuJiBie=5
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4
	end
	IF @KeMuJiBie=6
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5
	end
	IF @KeMuJiBie=7
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6
	end
	IF @KeMuJiBie=8
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7
	end
	IF @KeMuJiBie=9
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7+@Step8
	end
	IF @KeMuJiBie=10
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7+@Step8+@Step9
	end


	SET @KeMuLenSTR	=' AND Len(ItemBM) <=  '+ Cast(@KeMuLen as Varchar(2))





--@KeMuLen


     

Create Table #temptable1
      (ID  varchar(20) primary key,
   BILLID  varchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  varchar(50)  NULL,
   BILLDATE  datetime  NULL,
	[Debit] NUMERIC(20,2)  NULL ,
	[Credit] NUMERIC(20,2)  NULL ,
	[EAMOUNT]NUMERIC(20,2)  NULL ,
   zhaiyao  varchar(200)  NULL,
   ItemBM  varchar(200)  NULL,
   YYYYMM  varchar(200)  NULL

		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   ID , BILLID,BILLTYPE,BILLCODE,BILLDATE, '
           SELECT  @SQLSTR = @SQLSTR+' Debit,Credit,EAMOUNT ,brief,ItemBM,YYYYMM '
           SELECT  @SQLSTR = @SQLSTR+'  from CW_billflow   where yyyymmbill in (0,2)    '  + @WHERESTING+@BANKSTR +@KeMuLenSTR	
           SELECT  @SQLSTR = @SQLSTR+'  order by ItemBM,id '  
	print @SQLSTR


            EXEC( @SQLSTR)

Create Table #temptable2
      (ID  varchar(20) primary key,
   BILLID  varchar(50)  NULL,
   BILLTYPE  INTEGER,
   ItemBM  varchar(30)  NULL,
   JHD int  NULL,
   BILLCODE  varchar(100)  NULL,
   BILLDATE  datetime  NULL,
	[Debit] NUMERIC(20,2)  NULL ,
	[Credit] NUMERIC(20,2)  NULL ,
	[EAMOUNT]NUMERIC(20,2)  NULL ,
    zhaiyao varchar(300)  NULL,
    Memo    varchar(300)  NULL,
    NEWYYYYMM  varchar(300)  NULL
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	    declare INOUTMXBREP Cursor for Select  ID,BILLID,BILLTYPE , BILLCODE,BILLDATE,YYYYMM,
                                                       isnull(Debit,0) as Debit ,   isnull(Credit,0) as Credit ,
                                                     isnull(EAMOUNT,0) as EAMOUNT ,zhaiyao,ItemBM  from  #temptable1 
						     order by ItemBM,YYYYMM,id 
	    Open INOUTMXBREP

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@YYYYMM,
                                                               @Debit,@Credit,@EAMOUNT,@STRZhaiYao,@ItemBM

		Select @ItemBM00='AAAA'

	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
                       
			  SELECT  @NewYYYYMM=substring(@YYYYMM,1,4)+'年'+substring(@YYYYMM,5,2)+'月'


			IF   @ItemBM00<>@ItemBM 
			Begin

		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
	
			  select @BILLCODE=fullname,@JHD=JHD from ItemInfo where ItemBM=@ItemBM

	                  SELECT @BAMOUNT=BAMOUNT  FROM CW_billflow  WHERE  ItemBM=@ItemBM  AND YYYYMM=@Begin_YYYYMM   AND YYYYMMBILL=0
        	                                                      
	                  INSERT    INTO   #temptable2  (ID,BILLDATE, zhaiyao,EAMOUNT,NewYYYYMM,BILLCODE,ItemBM,JHD)
                                           VALUES  (@COUNTID ,@Begin_Date, '期初余额',@BAMOUNT,@NewYYYYMM,@BILLCODE,@ItemBM,@JHD)
			
				Select @ItemBM00=@ItemBM
			end


	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID


                    INSERT    INTO   #temptable2  (ID,BILLID,BILLTYPE, BILLDATE,NewYYYYMM,
                                                               Debit,Credit,EAMOUNT,zhaiyao,Memo,JHD)
                                           VALUES  (@COUNTID,@BILLID,@BILLTYPE, @BILLDATE,@NewYYYYMM,
                                                               @Debit,@Credit,@EAMOUNT,@STRZhaiYao,@Memo,@JHD)

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@YYYYMM,
                                                               @Debit,@Credit,@EAMOUNT,@STRZhaiYao,@ItemBM
 

	    END           ------- INOUTMXBREP  WHILE
	    close INOUTMXBREP
	    deallocate INOUTMXBREP




--------------------------

 SELECT *  FROM #temptable2         ORDER BY ID














----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG


















------------------

CREATE PROCEDURE [Check_BILL_NO] (@Table     varchar(30), 
                  @BILLCODE  varchar(50),      -- 出入库标志（单据开头表示RK表示入库，CK表示出库）
                  @FlagCun int output --单号
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --当前会计年月     
declare @idd varchar(8)                     --序列号
declare @BILLNOFLAG  varchar(1)                     --单据格式
declare @BILLW  varchar(20)                     --单据格式
begin

       SET @FlagCun=0
                                  --------- 入库单号 ---------       
      if @Table='STOREZCDM'
      begin
                 IF exists(select * from STOREZCDM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STOREYunFeiFKM'  
      begin
                 IF exists(select * from STOREYunFeiFKM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='INVOICEM'
      begin
                 IF exists(select * from INVOICEM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end


      if @Table='STOREGJRKM'
      begin
                 IF exists(select * from STOREGJRKM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end

      if @Table='STORELiuHM'
      begin
                 IF exists(select * from STORELiuHM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STOREXSDDM'
      begin
                 IF exists(select * from STOREXSDDM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STORECGDDM'
      begin
                 IF exists(select * from STORECGDDM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STORECGTHM'
      begin
                 IF exists(select * from STORECGTHM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STOREXSTHM'
      begin
                 IF exists(select * from STOREXSTHM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STOREFYKZM'
      begin
                 IF exists(select * from STOREFYKZM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STOREQTSRM'
      begin
                 IF exists(select * from STOREQTSRM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STOREMOVEM'
      begin
                 IF exists(select * from STOREMOVEM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STOREXSSKM'
      begin
                 IF exists(select * from STOREXSSKM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STORECGFKM'
      begin
                 IF exists(select * from STORECGFKM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STORECGRKM'
      begin
                 IF exists(select * from STORECGRKM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STOREXSCKM'
      begin
                 IF exists(select * from STOREXSCKM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end

      if @Table='STORECKDBM'
      begin
                 IF exists(select * from STORECKDBM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STORECKPDM'
      begin
                 IF exists(select * from STORECKPDM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STOREQTRKM'
      begin
                 IF exists(select * from STOREQTRKM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end

      if @Table='STOREQTCKM'
      begin
                 IF exists(select * from STOREQTCKM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STOREGJRKM'
      begin
                 IF exists(select * from STOREGJRKM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STOREJGDM'
      begin
                 IF exists(select * from STOREJGDM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STOREQGDM'
      begin
                 IF exists(select * from STOREQGDM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end

      if @Table='STORECSHM'
      begin
                 IF exists(select * from STORECSHM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STOREZFDM'
      begin
                 IF exists(select * from STOREZFDM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end



END









----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG






--------------------------------------------------------------------

---此过程取得单据的标识   ID
---此过程取得单据的标识   ID 为8位字符串

CREATE PROCEDURE [dbo].[Check_Cred_Code_NO] (@BILLID VARCHAR(20),@CredTypeID int ,@CredNo int ,@CredCode int,@CredNoCF int  output,@CredCodeCF int  output)
AS 
 
  declare @curKeyValue VARCHAR(20)
  declare @NextKeyValue VARCHAR(20)
  declare @YYYYMM varchar(6)                   --会计年月     
  declare @MAXBILLDATE DATEtime 
  declare @MINBILLDATE DATEtime 

BEGIN
--- 	 set @curkeyvalue='00000000'

		exec Get_Max_Min_Date @MAXBILLDATE output,@MINBILLDATE output


	if exists(select *  from CW_PingZhengM   where BILLDate >@MINBILLDATE AND BILLDate <= @MAXBILLDATE  and BILLID<>@BILLID and CredNo=@CredNo)
	begin
		set @CredNoCF=1
	end
	else
	begin
		set @CredNoCF=0
	end

	if exists(select *  from CW_PingZhengM   where BILLDate >@MINBILLDATE AND BILLDate <= @MAXBILLDATE AND CredTypeID=@CredTypeID and BILLID<>@BILLID and CredCode=@CredCode)
	begin
		set @CredCodeCF=1
	end
	else
	begin
		set @CredCodeCF=0
	end







END
  






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG





















CREATE PROCEDURE [DANJuXiaoShu_SET]  
                 (
                  @UnitQtySTR varchar(10),      ---单据编号   
                  @QuanTITYSTR varchar(10)      ---单据编号   
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---是否现款标志
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @VENDORID   varchar(15)               --明细存货编号
declare @String_QUANTITY   varchar(100)               --明细存货编号
declare @String_UNITQTY   varchar(100)               --明细存货编号



     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_QGD   --事物开始


       exec ('ALTER TABLE STORECSHD  ALTER COLUMN [QUANTITY] [numeric](20, '+@QuanTITYSTR+') NULL ')

       exec ('ALTER TABLE STORECSHD  ALTER COLUMN [UNITQTY] [numeric](20, '+@UnitQtySTR+') NULL ')

       exec ('ALTER TABLE STORECGDDD  ALTER COLUMN [QUANTITY] [numeric](20, '+@QuanTITYSTR+') NULL ')

       exec ('ALTER TABLE STORECGDDD  ALTER COLUMN [UNITQTY] [numeric](20, '+@UnitQtySTR+') NULL ')

       exec ('ALTER TABLE STORECGRKD  ALTER COLUMN [QUANTITY] [numeric](20, '+@QuanTITYSTR+') NULL ')

       exec ('ALTER TABLE STORECGRKD  ALTER COLUMN [UNITQTY] [numeric](20, '+@UnitQtySTR+') NULL ')

       exec ('ALTER TABLE STORECGTHD  ALTER COLUMN [QUANTITY] [numeric](20, '+@QuanTITYSTR+') NULL ')

       exec ('ALTER TABLE STORECGTHD  ALTER COLUMN [UNITQTY] [numeric](20, '+@UnitQtySTR+') NULL ')

       exec ('ALTER TABLE STOREXSDDD  ALTER COLUMN [QUANTITY] [numeric](20, '+@QuanTITYSTR+') NULL ')

       exec ('ALTER TABLE STOREXSDDD  ALTER COLUMN [UNITQTY] [numeric](20, '+@UnitQtySTR+') NULL ')

       exec ('ALTER TABLE STOREXSCKD  ALTER COLUMN [QUANTITY] [numeric](20, '+@QuanTITYSTR+') NULL ')

       exec ('ALTER TABLE STOREXSCKD  ALTER COLUMN [UNITQTY] [numeric](20, '+@UnitQtySTR+') NULL ')

       exec ('ALTER TABLE STOREXSTHD  ALTER COLUMN [QUANTITY] [numeric](20, '+@QuanTITYSTR+') NULL ')

       exec ('ALTER TABLE STOREXSTHD  ALTER COLUMN [UNITQTY] [numeric](20, '+@UnitQtySTR+') NULL ')

       exec ('ALTER TABLE STOREQTRKD  ALTER COLUMN [QUANTITY] [numeric](20, '+@QuanTITYSTR+') NULL ')

       exec ('ALTER TABLE STOREQTRKD  ALTER COLUMN [UNITQTY] [numeric](20, '+@UnitQtySTR+') NULL ')

       exec ('ALTER TABLE STOREQTCKD  ALTER COLUMN [QUANTITY] [numeric](20, '+@QuanTITYSTR+') NULL ')

       exec ('ALTER TABLE STOREQTCKD  ALTER COLUMN [UNITQTY] [numeric](20, '+@UnitQtySTR+') NULL ')

       exec ('ALTER TABLE STORECKDBD  ALTER COLUMN [QUANTITY] [numeric](20, '+@QuanTITYSTR+') NULL ')

       exec ('ALTER TABLE STORECKDBD  ALTER COLUMN [UNITQTY] [numeric](20, '+@UnitQtySTR+') NULL ')

       exec ('ALTER TABLE STOREJGDD  ALTER COLUMN [QUANTITY] [numeric](20, '+@QuanTITYSTR+') NULL ')

       exec ('ALTER TABLE STOREJGDD  ALTER COLUMN [UNITQTY] [numeric](20, '+@UnitQtySTR+') NULL ')

       exec ('ALTER TABLE STOREQGDD  ALTER COLUMN [QUANTITY] [numeric](20, '+@QuanTITYSTR+') NULL ')

       exec ('ALTER TABLE STOREQGDD  ALTER COLUMN [UNITQTY] [numeric](20, '+@UnitQtySTR+') NULL ')

       exec ('ALTER TABLE STOREQGADD  ALTER COLUMN [QUANTITY] [numeric](20, '+@QuanTITYSTR+') NULL ')

       exec ('ALTER TABLE STOREQGADD  ALTER COLUMN [UNITQTY] [numeric](20, '+@UnitQtySTR+') NULL ')









   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin  
    commit   transaction trans_QGD
   end
   else
   begin
      rollback transaction trans_QGD
   end

















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG








--------------------------------------------------------------------插入月结记录

CREATE PROCEDURE [DetailBillFlow_insert_YYYYMM]  
                 (	
	 @ITEMNO varchar(8),
	@GOODSID varchar(20),
	@STOREID varchar(8),
	@qty  NUMERIC(20,10) ,
	@PRICE  NUMERIC(20,10) ,
	 @DetailBillFlowID  varchar(8),
              @BILLID varchar(22)      ---单据编号   
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @NEWID varchar(15)               --明细存货编号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @B_CODE VARCHAR(25)
declare @B_ID INTEGER

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       

            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
	            IF (@INF_COSTINGTYPEID IN(1,3,6 ) )  AND 
                                               (not exists(select *  from DETAILBILLFLOW  where 
             		                                    (rtrim(GOODSID) = @GOODSID)
                           	                   and(rtrim(STOREID) = @STOREID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
		    insert into DetailBillFlow 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
		     BQTY,BPRICE,BAMOUNT,INQTY,INPRICE,OUTQTY,OUTPRICE,
		     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,INF_COSTINGTYPEID,
		     BATCHREFID,REFQTY,REFCOUNT )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@itemNo,@GoodsID,
		     0,0,0,0,0,Null,Null,
		     @QTY,@price,@StoreID,'F',@inoutFlag,@QTY*@PRICE,null,@INF_COSTINGTYPEID,
		     @B_ID,0,0  )    
	            END      ------IF   END
----------------------------------对于三种的计算方法的程序都是一样的只是判断条件不一样



----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













----------------------------------------------------------------------------
CREATE PROCEDURE [FYKZBILLTREE]  (  @INSQLSTRING  varchar(300)    )  --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 

Declare @SQL				varchar(8000)

 
BEGIN

	SELECT @SQL= 'select SUBSTRING(GOODSNOJS,1,4) as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWFYKZJSNO'
	SELECT @SQL=@SQL+'  WHERE   SUBSTRING(GOODSNOJS,1,4) in (select lcode FROM OUTTYPE)    ' +@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY SUBSTRING(GOODSNOJS,1,4)'
	SELECT @SQL=@SQL+' union '
	SELECT @SQL=@SQL+' select SUBSTRING(GOODSNOJS,5,4) as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWFYKZJSNO'
	SELECT @SQL=@SQL+'  where   SUBSTRING(GOODSNOJS,5,4) in (select lcode FROM OUTTYPE) '+@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY SUBSTRING(GOODSNOJS,5,4)'
	SELECT @SQL=@SQL+' union '
	SELECT @SQL=@SQL+' select SUBSTRING(GOODSNOJS,9,4) as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWFYKZJSNO'
	SELECT @SQL=@SQL+'  where   SUBSTRING(GOODSNOJS,9,4) in (select lcode FROM OUTTYPE) '+@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY SUBSTRING(GOODSNOJS,9,4)'
	SELECT @SQL=@SQL+' union '
	SELECT @SQL=@SQL+' select SUBSTRING(GOODSNOJS,13,4) as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWFYKZJSNO'
	SELECT @SQL=@SQL+'  where   SUBSTRING(GOODSNOJS,13,4) in (select lcode FROM OUTTYPE) '+@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY SUBSTRING(GOODSNOJS,13,4)'
	SELECT @SQL=@SQL+' union '
	SELECT @SQL=@SQL+' select SUBSTRING(GOODSNOJS,17,4) as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWFYKZJSNO'
	SELECT @SQL=@SQL+'  where   SUBSTRING(GOODSNOJS,17,4) in (select lcode FROM OUTTYPE) '+@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY SUBSTRING(GOODSNOJS,17,4)'
	SELECT @SQL=@SQL+' union '
	SELECT @SQL=@SQL+' select SUBSTRING(GOODSNOJS,21,4) as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWFYKZJSNO'
	SELECT @SQL=@SQL+'  where   SUBSTRING(GOODSNOJS,21,4) in (select lcode FROM OUTTYPE) '+@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY SUBSTRING(GOODSNOJS,21,4)'
	SELECT @SQL=@SQL+' union '
	SELECT @SQL=@SQL+' select  STOREID as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWFYKZJSNO'
	SELECT @SQL=@SQL+'  where   1 = 1 '+@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY STOREID '
		EXEC(@SQL)
----注意OUTTYPE  中的LCODE不能和GOODS中的STOREID 重码，以后补充检测过程
------------------------------------------------------------------------------------


END






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












CREATE PROCEDURE GETALLPRICE(@GOODSID  varchar(20)  ,         ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
						           @DXSTOPPRICE   NUMERIC(20,10)    OUTPUT,
						           @DXSDOWNPRICE   NUMERIC(20,10)    OUTPUT,
						           @DXSAVGPRICE   NUMERIC(20,10)    OUTPUT,
						           @MXSTOPPRICE   NUMERIC(20,10)    OUTPUT,
						           @MXSDOWNPRICE   NUMERIC(20,10)    OUTPUT,
						           @MXSAVGPRICE   NUMERIC(20,10)    OUTPUT,
						           @DCGTOPPRICE   NUMERIC(20,10)    OUTPUT,
						           @DCGDOWNPRICE   NUMERIC(20,10)    OUTPUT,
						           @DCGAVGPRICE   NUMERIC(20,10)    OUTPUT,
						           @MCGTOPPRICE   NUMERIC(20,10)    OUTPUT,
						           @MCGDOWNPRICE   NUMERIC(20,10)    OUTPUT,
						           @MCGAVGPRICE   NUMERIC(20,10)    OUTPUT,
						           @MEQTY   NUMERIC(20,10)    OUTPUT,
						           @EQTY   NUMERIC(20,10)    OUTPUT
                         
                                                      )   --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @YYYYMM  varchar(8),      --------为当前会计期间
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000)
Declare    @SUM_1   NUMERIC(20,6)   
Declare    @SUM_0   NUMERIC(20,6)   
Declare    @SUM_unitqty   NUMERIC(20,6)   
Declare    @MXSTOPPRICE_1   NUMERIC(20,6)   
Declare    @MXSDOWNPRICE_1   NUMERIC(20,6)   
Declare    @MCGTOPPRICE_1   NUMERIC(20,6)   
Declare    @MCGDOWNPRICE_1   NUMERIC(20,6)   
Declare    @SQLSTR00   varchar(8000)

set @temp_year  = convert(varchar,year(getdate()))
set @temp_month = substring('00',1,2-len(convert(varchar,month(getdate()))))+convert(varchar,month(getdate()))
set @temp_day   = substring('00',1,2-len(convert(varchar,day(getdate()))))+convert(varchar,day(getdate()))
set @now_date   = @temp_year + @temp_month +@temp_day

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
Create Table #VIEWXSCK00
      (   GOODSID  nvarchar(50)  NULL,
	[unitprice] NUMERIC(20,10)  NULL ,
	[UNITQTY] NUMERIC(20,10)  NULL ,
	[quantity] NUMERIC(20,10)  NULL ,
	[PRICETYPE] int
		)

     select  @SQLSTR00=' INSERT INTO #VIEWXSCK00 Select top 10  GOODSID,unitprice,UNITQTY,quantity,PRICETYPE from   VIEWXSCKGOODSCODE WHERE GOODSID='+ @GOODSID +' order by  billdate  desc'
     exec (@SQLSTR00)

                      SELECT @DXSTOPPRICE=(SELECT isnull(max(unitprice),0)  AS  unitprice  FROM    #VIEWXSCK00  WHERE PRICETYPE=1)


                      SELECT @DXSDOWNPRICE=(SELECT isnull(mIN(unitprice),0)  AS  unitprice  FROM   #VIEWXSCK00  where PRICETYPE=1)
                      
                      SELECT @DXSAVGPRICE=(SELECT isnull(sum(unitprice*quantity)/sum(quantity),0)   AS  unitprice  FROM     #VIEWXSCK00  WHERE PRICETYPE=1 AND  quantity  >0 )  

---                      SELECT @MXSTOPPRICE=(SELECT isnull(max(unitprice),0)  AS  unitprice  FROM    VIEWXSCKGOODSCODE   where BILLID IN (Select top 10 BILLID from   VIEWXSCKGOODSCODE  WHERE PRICETYPE=0  AND  GOODSID=@GOODSID order by  billdate  desc))

                      SELECT @MXSTOPPRICE=(SELECT isnull(max(unitprice),0)  AS  unitprice  FROM     #VIEWXSCK00  WHERE PRICETYPE=0  )

                      SELECT @MXSTOPPRICE_1=(SELECT isnull(max(unitprice*quantity/UNITQTY),0)  AS  unitprice  FROM    #VIEWXSCK00 WHERE PRICETYPE=1 AND UNITQTY >0  )
				iF  @MXSTOPPRICE < @MXSTOPPRICE_1  
				begin
				   set  @MXSTOPPRICE = @MXSTOPPRICE_1
				end


                      SELECT @MXSDOWNPRICE=(SELECT isnull(MIN(unitprice),0)  AS  unitprice  FROM     #VIEWXSCK00   WHERE PRICETYPE=0  )

                      SELECT @MXSDOWNPRICE_1=(SELECT isnull(MIN(unitprice*quantity/UNITQTY),0)  AS  unitprice  FROM     #VIEWXSCK00  WHERE PRICETYPE=1 AND UNITQTY >0 )

				iF  (@MXSDOWNPRICE > @MXSDOWNPRICE_1)  OR (@MXSDOWNPRICE =0)
				begin
				   set  @MXSDOWNPRICE = @MXSDOWNPRICE_1
				end


                      SELECT @SUM_1=(SELECT   isnull(sum(unitprice*quantity),0)  FROM     #VIEWXSCK00 WHERE PRICETYPE=1  AND  unitqty  >0 )  
                      SELECT @SUM_0=(SELECT   isnull(sum(unitprice*unitqty),0)  FROM     #VIEWXSCK00  WHERE PRICETYPE=0  AND  unitqty  >0 )  
                      SELECT @SUM_unitqty=(SELECT   sum(unitqty)  FROM    #VIEWXSCK00  WHERE   unitqty  >0 )  
		      IF isnull(@SUM_unitqty,0) <>0	
                      SELECT @MXSAVGPRICE=(@SUM_1+@SUM_0)/@SUM_unitqty
		      ELSE
                      SELECT @MXSAVGPRICE=0




Create Table #VIEWCGRK00
      (   GOODSID  nvarchar(50)  NULL,
	[unitprice] NUMERIC(20,10)  NULL ,
	[UNITQTY] NUMERIC(20,10)  NULL ,
	[quantity] NUMERIC(20,10)  NULL ,
	[PRICETYPE] int
		)

     select  @SQLSTR00=' INSERT INTO #VIEWCGRK00 Select top 10  GOODSID,unitprice,UNITQTY,quantity,PRICETYPE from   VIEWCGRKGOODSCODE WHERE GOODSID='+ @GOODSID +' order by  billdate  desc'
     exec (@SQLSTR00)

                      SELECT @DCGTOPPRICE=(SELECT isnull(max(unitprice),0)  AS  unitprice  FROM    #VIEWCGRK00  WHERE PRICETYPE=1)


                      SELECT @DCGDOWNPRICE=(SELECT isnull(mIN(unitprice),0)  AS  unitprice  FROM   #VIEWCGRK00  where PRICETYPE=1)
                      
                      SELECT @DCGAVGPRICE=(SELECT isnull(sum(unitprice*quantity)/sum(quantity),0)   AS  unitprice  FROM     #VIEWCGRK00  WHERE PRICETYPE=1 AND  quantity  >0 )  

---                      SELECT @MCGTOPPRICE=(SELECT isnull(max(unitprice),0)  AS  unitprice  FROM    VIEWCGRKGOODSCODE   where BILLID IN (Select top 10 BILLID from   VIEWCGRKGOODSCODE  WHERE PRICETYPE=0  AND  GOODSID=@GOODSID order by  billdate  desc))

                      SELECT @MCGTOPPRICE=(SELECT isnull(max(unitprice),0)  AS  unitprice  FROM     #VIEWCGRK00  WHERE PRICETYPE=0  )

                      SELECT @MCGTOPPRICE_1=(SELECT isnull(max(unitprice*quantity/UNITQTY),0)  AS  unitprice  FROM    #VIEWCGRK00 WHERE PRICETYPE=1 AND UNITQTY >0  )
				iF  @MCGTOPPRICE < @MCGTOPPRICE_1  
				begin
				   set  @MCGTOPPRICE = @MCGTOPPRICE_1
				end


                      SELECT @MCGDOWNPRICE=(SELECT isnull(MIN(unitprice),0)  AS  unitprice  FROM     #VIEWCGRK00   WHERE PRICETYPE=0  )

                      SELECT @MCGDOWNPRICE_1=(SELECT isnull(MIN(unitprice*quantity/UNITQTY),0)  AS  unitprice  FROM     #VIEWCGRK00  WHERE PRICETYPE=1 AND UNITQTY >0 )

				iF  (@MCGDOWNPRICE > @MCGDOWNPRICE_1)  OR (@MCGDOWNPRICE =0)
				begin
				   set  @MCGDOWNPRICE = @MCGDOWNPRICE_1
				end


                      SELECT @SUM_1=(SELECT   isnull(sum(unitprice*quantity),0)  FROM     #VIEWCGRK00 WHERE PRICETYPE=1  AND  unitqty  >0 )  
                      SELECT @SUM_0=(SELECT   isnull(sum(unitprice*unitqty),0)  FROM     #VIEWCGRK00  WHERE PRICETYPE=0  AND  unitqty  >0 )  
                      SELECT @SUM_unitqty=(SELECT   sum(unitqty)  FROM    #VIEWCGRK00  WHERE   unitqty  >0 )  
		      IF isnull(@SUM_unitqty,0) <>0	
                      SELECT @MCGAVGPRICE=(@SUM_1+@SUM_0)/@SUM_unitqty
		      ELSE
                      SELECT @MCGAVGPRICE=0





----------------------------------------------------
		SELECT @SQLSTR='	INSERT INTO  #GOODSTEMP      select  I.GOODSID,       '
		SELECT @SQLSTR=@SQLSTR+'  ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0)  as MEQTY, '   --期末数量
		SELECT @SQLSTR=@SQLSTR+'  ISNULL(B.BQTY,0)+ isnull(E.INQTY,0)  as EQTY   '   --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from Goods    AS  I'
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(INQTY*INOUTFLAG)  as INQTY  ,sum(MINQTY*INOUTFLAG)  as MINQTY '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(BQTY) as BQTY ,sum(MBQTY) as MBQTY'
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where    I.GOODSID   = ' +char(39)+@GOODSID+char(39)
------------------------------------------------------------------------
Create Table #GOODSTEMP
      (   GOODSID  nvarchar(50)  NULL,
	[MEQTY] NUMERIC(20,10)  NULL ,
	[EQTY] NUMERIC(20,10)  NULL 
		)

 		EXEC(@SQLSTR)
                      SELECT  @EQTY=(SELECT isnull(EQTY,0)  AS  EQTY  FROM #GOODSTEMP )
                      SELECT  @MEQTY=(SELECT isnull(MEQTY,0)  AS  MEQTY  FROM #GOODSTEMP )






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











----------------------------------------------------------------------------

CREATE PROCEDURE GETCLIENTIDEAMOUNT(@CLIENTID varchar(8) ,                        -----如果为0000则全部仓库
						           @EAMOUNT   NUMERIC(20,10)    OUTPUT
                         
                                                      )   --APSOFTENCRYPTION       WITH ENCRYPTION
as




Declare    @MAXID   varchar(80)

  SELECT  @MAXID=MAX(ID)  FROM CLIENTbillflow  WHERE  CLIENTID=@CLIENTID  AND YYYYMMBILL=1

                        IF @MAXID IS NULL
 			BEGIN
			SET  @EAMOUNT=0
			END
                        ELSE
			BEGIN
                         SELECT @EAMOUNT=EAMOUNT   FROM   CLIENTbillflow  WHERE ID=@MAXID
			END







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG










----------------------------------------------------------------------------

CREATE PROCEDURE GETGOODSIDEQTY(@STOREID varchar(8) ,                        -----如果为0000则全部仓库
						           @GOODSID  varchar(20)  ,         ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
                                                                                           @YYYYMM  varchar(8),      --------为当前会计期间
						           @EQTY   NUMERIC(20,10)    OUTPUT
                         
                                                      )   --APSOFTENCRYPTION       WITH ENCRYPTION
as



Declare 
        @SQLSTR   varchar(8000)

Declare    @GOODSIDSTR   varchar(80)
Declare    @STOREIDSTR   varchar(80)


----------------------------------------------------
		 SET @GOODSIDSTR = '  AND   GOODSID = '+char(39)+ @GOODSID+char(39)
		 IF   @STOREID='0000'
		BEGIN
		 SET @STOREIDSTR = '    '
		END
		ELSE
		BEGIN
		 SET @STOREIDSTR = '  AND   STOREID = '+char(39)+ @STOREID+char(39)
		END
		SELECT @SQLSTR='	INSERT  #GOODSTEMP      select  I.GOODSID,       '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)+ isnull(E.INQTY,0)  as EQTY '   --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from Goods    AS  I'
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(INQTY*INOUTFLAG)  as INQTY  '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)  +@STOREIDSTR +@GOODSIDSTR               --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(BQTY) as BQTY '
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) +@STOREIDSTR+@GOODSIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where    I.GOODSID   = ' +char(39)+@GOODSID+char(39)
------------------------------------------------------------------------
Create Table #GOODSTEMP
      (   GOODSID  nvarchar(50)  NULL,
	[EQTY] NUMERIC(20,10)  NULL 
		)

 		EXEC(@SQLSTR)
                      SELECT  @EQTY=(SELECT isnull(EQTY,0)  AS  EQTY  FROM #GOODSTEMP )




----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG










----------------------------------------------------------------------------

CREATE PROCEDURE GETGOODSIDMEQTY(@STOREID varchar(8) ,                        -----如果为0000则全部仓库
						           @GOODSID  varchar(20)  ,         ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
                                                                                           @YYYYMM  varchar(8),      --------为当前会计期间
						           @MEQTY   NUMERIC(20,10)    OUTPUT
                         
                                                      )   --APSOFTENCRYPTION       WITH ENCRYPTION
as



Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000)

Declare    @GOODSIDSTR   varchar(80)
Declare    @STOREIDSTR   varchar(80)

set @temp_year  = convert(varchar,year(getdate()))
set @temp_month = substring('00',1,2-len(convert(varchar,month(getdate()))))+convert(varchar,month(getdate()))
set @temp_day   = substring('00',1,2-len(convert(varchar,day(getdate()))))+convert(varchar,day(getdate()))
set @now_date   = @temp_year + @temp_month +@temp_day

----------------------------------------------------
		 SET @GOODSIDSTR = '  AND   GOODSID = '+char(39)+ @GOODSID+char(39)
		 IF   @STOREID='0000'
		BEGIN
		 SET @STOREIDSTR = '    '
		END
		ELSE
		BEGIN
		 SET @STOREIDSTR = '  AND   STOREID = '+char(39)+ @STOREID+char(39)
		END
		SELECT @SQLSTR='	INSERT  #GOODSTEMP      select  I.GOODSID,       '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0)  as MEQTY '   --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from Goods    AS  I'
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(MINQTY*INOUTFLAG)  as MINQTY  '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)  +@STOREIDSTR +@GOODSIDSTR               --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(MBQTY) as MBQTY '
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) +@STOREIDSTR+@GOODSIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where    I.GOODSID   = ' +char(39)+@GOODSID+char(39)
------------------------------------------------------------------------
Create Table #GOODSTEMP
      (   GOODSID  nvarchar(50)  NULL,
	[MEQTY] NUMERIC(20,10)  NULL 
		)

 		EXEC(@SQLSTR)
                      SELECT  @MEQTY=(SELECT isnull(MEQTY,0)  AS  MEQTY  FROM #GOODSTEMP )







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------

CREATE PROCEDURE GETGOODSSQL(@STOREID varchar(8) ,                        -----如果为0000则全部仓库
						           @LCODE  varchar(10),             ---如果LCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSCODE  varchar(20),             ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSNAME  varchar(20),             ---如果GOODSNAME  为‘GGGG’表示不对类别进行查询
                                                                                           @INF_COSTINGTYPEID   smallint      --------同价调拨标志   0  代表 不作为过滤条件
                         
                                                      )     --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @WHERESTING   varchar(1800),
        @STOREIDSTR   varchar(100)

--@WHERESTR='  and 1=1 '
		if     NOT (@LCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = '  AND   GOODSID IN ( select  GOODSID from Goods   where  LCODE LIKE   '+CHAR(39)+@LCODE+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  ='     '
 		END
		if     NOT (@GOODSCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   GOODSID IN ( select  GOODSID from Goods   where  CODE LIKE   '+CHAR(39)+'%'+@GOODSCODE+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  =@WHERESTING+'     '
 		END
		if     NOT (@GOODSNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   GOODSID IN ( select  GOODSID from Goods   where  NAME  LIKE   '+CHAR(39)+'%'+@GOODSNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END
		if     NOT (@INF_COSTINGTYPEID=0)
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND  GOODSID IN ( select  GOODSID from Goods   where INF_COSTINGTYPEID =  '+str(@INF_COSTINGTYPEID)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END
		if     NOT (@STOREID='0000')
                           BEGIN
	                           SELECT    @STOREIDSTR   = '  AND   STOREID =  '+@STOREID
                           END
                           ELSE
                           BEGIN
			SELECT    @STOREIDSTR   = '     '
 		END

                       print   @WHERESTING
----------------------------------------------------
                         SELECT  @SQLSTR=' SELECT  *  FROM GOODS WHERE   1 = 1  ' +@WHERESTING
		EXEC(@SQLSTR)





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











CREATE PROCEDURE GETGoodsIDEQTYANDALL(@GOODSID  varchar(20)  ,         ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
				   @StoreID  varchar(20), 
			           @EQTY   NUMERIC(20,10)    OUTPUT,
			           @StoreIDEQTY   NUMERIC(20,10)    OUTPUT
                                                      )   --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @YYYYMM  varchar(8),      --------为当前会计期间
        @SQLSTR   varchar(8000)


     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     

----------------------------------------------------
		SELECT @SQLSTR='	INSERT  #GOODSTEMP     select  I.GOODSID,       '
		SELECT @SQLSTR=@SQLSTR+'  ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0)  as MEQTY, '   --期末数量
		SELECT @SQLSTR=@SQLSTR+'  ISNULL(B.BQTY,0)+ isnull(E.INQTY,0)  as EQTY   '   --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from Goods    AS  I'
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(INQTY*INOUTFLAG)  as INQTY  ,sum(MINQTY*INOUTFLAG)  as MINQTY '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(BQTY) as BQTY ,sum(MBQTY) as MBQTY'
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where    I.GOODSID   = ' +char(39)+@GOODSID+char(39)
------------------------------------------------------------------------
Create Table #GOODSTEMP
      (   GOODSID  nvarchar(50)  NULL,
	[MEQTY] NUMERIC(20,10)  NULL ,
	[EQTY] NUMERIC(20,10)  NULL 
		)

 		EXEC(@SQLSTR)
                      SELECT  @EQTY=(SELECT isnull(EQTY,0)  AS  EQTY  FROM #GOODSTEMP )
--                      SELECT  @MEQTY=(SELECT isnull(MEQTY,0)  AS  MEQTY  FROM #GOODSTEMP )
---                      SELECT  @EQTY=(SELECT isnull(EQTY,0)  AS  EQTY  FROM #GOODSTEMP )

                      SELECT  @EQTY=0

                      EXEC   GETGOODSIDEQTY  @STOREID,@GOODSID,@YYYYMM,@EQTY=@STOREIDEQTY   OUTPUT






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG









--------------------------------------------------------------------

---此过程取得单据的标识   ID
---此过程取得单据的标识   ID 为8位字符串

CREATE PROCEDURE [GETKEYCodeKEYVALUE] (@TABLENAME VARCHAR(48),@Lcode VARCHAR(48),
				@R_KEYCode VARCHAR(20)  output,
				@R_KeyValue VARCHAR(20)  output)    --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 
  declare @curKEYCode VARCHAR(20)
  declare @NextKEYCode VARCHAR(20)
  declare @MaxCode VARCHAR(50)
  declare @SQLSTR VARCHAR(5000)
  declare @curKeyValue VARCHAR(20)
  declare @NextKeyValue VARCHAR(20)

BEGIN
--- 	 set @curKEYCode='00000000'
Create Table #TempCodeValue
      (   ABCD    varchar(50)  NULL
		)


		SET @SqlSTR=' INSERT  #TempCodeValue  '
		SET @SqlSTR=@SqlSTR+' select Max(Code) from '+@TableName+' where code like '+Char(39)+@Lcode+'%'+Char(39)		
		exec (@SqlSTR)
		Select @MaxCode=(SELect ABCD  from #TempCodeValue)


----Select substring('10.1.37',len('10.1')+2,len('10.1.37')-len('10.1')-1)

	  SET @curKEYCode=substring(@MaxCode,len(@Lcode)+2,len(@MaxCode)-len(@Lcode)-1)

	  If  (@curKEYCode<>'') and  (NOT (@curKEYCode IS NULL)) AND (CHARINDEX('.',@curKEYCode)=0)
	  begin
	          set @NextKEYCode = rtrim(convert(char,convert(int,@curKEYCode)+1))
		  set @R_KEYCode = @Lcode+'.'+@NextKEYCode

	  end
	  else
	  begin

		  select @curKEYCode=keyvalue from keyvaluetable   where TableName=@TableName 
        	  set @NextKEYCode = rtrim(convert(char,convert(int,@curKEYCode)+1))
	          set @NextKEYCode = substring('00000000',1,8-len(@NextKEYCode))+@NextKEYCode

		  if (@curKEYCode  is NULL)  or (not (len(@curKEYCode)=8 ) )
		  begin
		    set @R_KEYCode='00000001'
		    delete from keyvaluetable where TableName=@TableName
		    insert into keyvaluetable values (@TableName,@R_KEYCode)
		  end
		  else
		  begin
		    update keyvaluetable set keyvalue=@NextKEYCode    where TableName=@TableName
		    set @R_KEYCode = @NextKEYCode
		  end
	  end


-------------------以上部分是取Code------以下部分是取KeyValue---------------------------------

	  select @curkeyvalue=keyvalue from keyvaluetable   where TableName=@TableName 
          set @NextKeyValue = rtrim(convert(char,convert(int,@curkeyvalue)+1))
          set @NextKeyValue = substring('00000000',1,8-len(@NextKeyValue))+@NextKeyValue

	  if (@curkeyvalue  is NULL)  or (not (len(@curkeyvalue)=8 ) )
	  begin
	    set @R_KeyValue='00000001'
	    delete from keyvaluetable where TableName=@TableName
	    insert into keyvaluetable values (@TableName,@R_KeyValue)
	  end
	  else
	  begin
	    update keyvaluetable set keyvalue=@NextKeyValue    where TableName=@TableName
	    set @R_KeyValue = @NextKeyValue
	  end


END
  







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG








--------------------------------------------------------------------

---此过程取得单据的标识   ID
---此过程取得单据的标识   ID 为8位字符串

CREATE PROCEDURE [GETKEYVALUE] (@TABLENAME VARCHAR(48),@R_KeyValue VARCHAR(20)  output)    --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 
  declare @curKeyValue VARCHAR(20)
  declare @NextKeyValue VARCHAR(20)

BEGIN
--- 	 set @curkeyvalue='00000000'
	  select @curkeyvalue=keyvalue from keyvaluetable   where TableName=@TableName 
          set @NextKeyValue = rtrim(convert(char,convert(int,@curkeyvalue)+1))
          set @NextKeyValue = substring('00000000',1,8-len(@NextKeyValue))+@NextKeyValue

	  if (@curkeyvalue  is NULL)  or (not (len(@curkeyvalue)=8 ) )
	  begin
	    set @R_KeyValue='00000001'
	    delete from keyvaluetable where TableName=@TableName
	    insert into keyvaluetable values (@TableName,@R_KeyValue)
	  end
	  else
	  begin
	    update keyvaluetable set keyvalue=@NextKeyValue    where TableName=@TableName
	    set @R_KeyValue = @NextKeyValue
	  end
END
  






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












--------------------------------------------------------------------

---此过程取得单据的标识   ID
---此过程取得单据的标识   ID 为2位字符串

CREATE PROCEDURE [GETKEYVALUE00] (@TABLENAME VARCHAR(48),@R_KeyValue VARCHAR(2)  output)    --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 
  declare @curKeyValue VARCHAR(20)
  declare @NextKeyValue VARCHAR(20)

BEGIN
--- 	 set @curkeyvalue='00000000'
	  select @curkeyvalue=keyvalue from keyvaluetable   where TableName=@TableName 
          set @NextKeyValue = rtrim(convert(char,convert(int,@curkeyvalue)+1))
          set @NextKeyValue = substring('00',1,2-len(@NextKeyValue))+@NextKeyValue

	  if (@curkeyvalue  is NULL)  or (not (len(@curkeyvalue)=2 ) )
	  begin
	    set @R_KeyValue='01'
	    delete from keyvaluetable where TableName=@TableName
	    insert into keyvaluetable values (@TableName,@R_KeyValue)
	  end
	  else
	  begin
	    update keyvaluetable set keyvalue=@NextKeyValue    where TableName=@TableName
	    set @R_KeyValue = @NextKeyValue
	  end
END
  






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













--------------------------------------------------------------------

---此过程取得单据的标识   ID
---此过程取得单据的标识   ID 为2位字符串

CREATE PROCEDURE [GETKEYVALUE4] (@TABLENAME VARCHAR(48),@R_KeyValue VARCHAR(4)  output)    --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 
  declare @curKeyValue VARCHAR(20)
  declare @NextKeyValue VARCHAR(20)

BEGIN
--- 	 set @curkeyvalue='00000000'
	  select @curkeyvalue=keyvalue from keyvaluetable   where TableName=@TableName 
          set @NextKeyValue = rtrim(convert(char,convert(int,@curkeyvalue)+1))
          set @NextKeyValue = substring('0000',1,4-len(@NextKeyValue))+@NextKeyValue

	  if (@curkeyvalue  is NULL)  or (not (len(@curkeyvalue)=4 ) )
	  begin
	    set @R_KeyValue='0001'
	    delete from keyvaluetable where TableName=@TableName
	    insert into keyvaluetable values (@TableName,@R_KeyValue)
	  end
	  else
	  begin
	    update keyvaluetable set keyvalue=@NextKeyValue    where TableName=@TableName
	    set @R_KeyValue = @NextKeyValue
	  end
END
  







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











----------------------------------------------------------------------------

CREATE PROCEDURE GETVENDORIDEAMOUNT(@VENDORID varchar(8) ,                        -----如果为0000则全部仓库
						           @EAMOUNT   NUMERIC(20,10)    OUTPUT
                         
                                                      )   --APSOFTENCRYPTION       WITH ENCRYPTION
as




Declare    @MAXID   varchar(80)

  SELECT  @MAXID=MAX(ID)  FROM VENDORbillflow  WHERE  VENDORID=@VENDORID  AND YYYYMMBILL=1

                        IF @MAXID IS NULL
 			BEGIN
			SET  @EAMOUNT=0
			END
                        ELSE
			BEGIN
                         SELECT @EAMOUNT=EAMOUNT   FROM   VENDORbillflow  WHERE ID=@MAXID
			END







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG










--------------------------------------------------------------------

---此过程取得单据的标识   ID
---此过程取得单据的标识   ID 为8位字符串

CREATE PROCEDURE [dbo].[GETXSPrice] (@GoodsID VARCHAR(48),@DXSPrice  NUMERIC(20,2)    OUTPUT,
							@MXSPrice   NUMERIC(20,10)    OUTPUT
)    --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 
  declare @SumAMT NUMERIC(20,10)
  declare @MinITEMNO  varchar(20)
  declare @SumQuantity NUMERIC(20,10)
  declare @printcount int

BEGIN

---------------取销售定价模式
---------------@printcount=1 按品种定价
---------------@printcount=2 按采购批次定价

---------------@

	          select  @printcount=printcount from ACCINFO where GUID='0001'
     if @printcount=2 
	    begin               
	          select  @MinITEMNO=Min(ITEMNO) from CGRKGoodsPrice where GOODSID=@GOODSID  AND ( DEQTY>0 OR MEQTY>0)
           if @MinITEMNO is not null
           begin
              select  @DXSPrice=ISNULL(DSPrice,0),@MXSPrice=ISNULL(MSPrice,0)  from CGRKGoodsPrice where ITEMNO=@MinITEMNO
			end
			else
			begin
              select  @DXSPrice=ISNULL(DSPrice,0) ,@MXSPrice=ISNULL(MQTYSPRICE,0)  from GOODS where  GOODSID=@GOODSID		
			end
        end
        else
        begin
              select  @DXSPrice=ISNULL(DSPrice,0) ,@MXSPrice=ISNULL(MQTYSPRICE,0)  from GOODS where  GOODSID=@GOODSID		
        end
               

END
  








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG









--------------------------------------------------------------------

---此过程取得单据的标识   ID
---此过程取得单据的标识   ID 为8位字符串

CREATE PROCEDURE [GETXSPriceDays] (@GoodsID VARCHAR(48),@R_10DayPrce  NUMERIC(20,10)    OUTPUT,
							@R_20DayPrce  NUMERIC(20,10)    OUTPUT,
							@R_30DayPrce  NUMERIC(20,10)    OUTPUT,
							@R_60DayPrce  NUMERIC(20,10)    OUTPUT
)    --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 
  declare @SumAMT NUMERIC(20,10)
  declare @SumQuantity NUMERIC(20,10)

BEGIN

	  SELECT  @SumAMT=Sum(AMT) FROM VIEWXSCKGOODSCODE  where  billdate >= convert(varchar(10),dateadd(day ,-10 ,getdate()),120) 
	  SELECT  @SumQuantity=Sum(Quantity) FROM VIEWXSCKGOODSCODE where  billdate >= convert(varchar(10),dateadd(day ,-10 ,getdate()),120) 

          Select @R_10DayPrce=@SumAMT/@SumQuantity                                        

	  SELECT  @SumAMT=Sum(AMT) FROM VIEWXSCKGOODSCODE  where  billdate >= convert(varchar(10),dateadd(day ,-20 ,getdate()),120) 
	  SELECT  @SumQuantity=Sum(Quantity) FROM VIEWXSCKGOODSCODE where  billdate >= convert(varchar(10),dateadd(day ,-20 ,getdate()),120) 

          Select @R_20DayPrce=@SumAMT/@SumQuantity                                        

	  SELECT  @SumAMT=Sum(AMT) FROM VIEWXSCKGOODSCODE  where  billdate >= convert(varchar(10),dateadd(day ,-30 ,getdate()),120) 
	  SELECT  @SumQuantity=Sum(Quantity) FROM VIEWXSCKGOODSCODE where  billdate >= convert(varchar(10),dateadd(day ,-30 ,getdate()),120) 

          Select @R_30DayPrce=@SumAMT/@SumQuantity                                        

	  SELECT  @SumAMT=Sum(AMT) FROM VIEWXSCKGOODSCODE  where  billdate >= convert(varchar(10),dateadd(day ,-60 ,getdate()),120) 
	  SELECT  @SumQuantity=Sum(Quantity) FROM VIEWXSCKGOODSCODE where  billdate >= convert(varchar(10),dateadd(day ,-60 ,getdate()),120) 

          Select @R_60DayPrce=@SumAMT/@SumQuantity                                        



END
  







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











----------------------------------------------------------------------------
CREATE PROCEDURE [GET_APRICE ]  (  @GOODSID varchar(22),      ---单据编号   
	     @STOREID varchar(22),  
                  @FLAGPOST INT,      ---记帐标志
  	     @DETAILBILLFLOWID varchar(30), 
  	     @REDETAILBILLFLOWID varchar(30), 
	@APRICE NUMERIC(20,10)   output)     --APSOFTENCRYPTION       WITH ENCRYPTION
AS 


declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @STOREHSFS   INTEGER
declare @MAXID   varchar(30)

 
BEGIN

	       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )      


            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)

                 SELECT   @APRICE=0.00 

	    IF   @FLAGPOST = 0  --THEN
	    BEGIN
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
			IF  @INF_COSTINGTYPEID=1    OR  @INF_COSTINGTYPEID=3
			BEGIN
                                            SELECT  @MAXID=(SELECT MAX(ID)  FROM  DETAILBILLFLOW   WHERE GOODSID=@GOODSID  AND STOREID=@STOREID  and  YYYYMMBILL=1)
		                 SELECT  @APRICE =EPRICE    FROM DETAILBILLFLOW  WHERE GOODSID = @GOODSID  AND STOREID=@STOREID  AND ID=@MAXID
			END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
			IF  @INF_COSTINGTYPEID=1    OR @INF_COSTINGTYPEID=3
			BEGIN
                                            SELECT  @MAXID=(SELECT MAX(ID)  FROM  DETAILBILLFLOW   WHERE GOODSID=@GOODSID and  YYYYMMBILL=1)
		                 SELECT  @APRICE = EPRICE    FROM DETAILBILLFLOW   WHERE GOODSID = @GOODSID  AND ID=@MAXID
			END
                            END
 		IF  @INF_COSTINGTYPEID=2    
		BEGIN
	                 SELECT  @APRICE =INPRICE    FROM DETAILBILLFLOW  
             	               WHERE ID= @REDETAILBILLFLOWID
		END
	    END
	    IF  ( @FLAGPOST = 1) 
	    BEGIN
	                 SELECT  @APRICE =INPRICE    FROM DETAILBILLFLOW  
             		               WHERE ID= @DETAILBILLFLOWID
                              if  @APRICE is null
                              begin
                                      set @APRICE=0.00
		   end
	    END



END
  






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG






















------------------

CREATE PROCEDURE [GET_BILL_NO] (@Table     varchar(30), 
                  @sysdate   varchar(10),         ---系统时间格式为  2004-02-02
                  @INOUTFlag varchar(2),      -- 出入库标志（单据开头表示RK表示入库，CK表示出库）
                  @bill_no_selfd varchar(22) output --单号
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --当前会计年月     
declare @idd varchar(8)                     --序列号
declare @BILLNOFLAG  varchar(1)                     --单据格式
declare @BILLW  varchar(20)                     --单据格式
declare @YYYYMM_FLAG  INTEGER

begin

       set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
               ---@BILLNOFLAG  返回单据号的格式{[0]代表RK-2004-03-12-0001;[1]代表RK-2004-03-0001}
       set @BILLNOFLAG   = (select optionvalue from accoptions where optionname ='BILLNOFLAG')
       SET @BILLW='DSDSD'

-------解决所在的会计期间的
-------根据日期来判断所在的会计区间
-------
      EXEC  BETWEEN_CURR_YYYYMM  @sysdate , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@YYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

----        print @YYYYMM

if (@BILLNOFLAG = '1')
begin           
                                  --------- 入库单号 ---------
      if @Table='STOREZFDM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREZFDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREZFDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREXSFPM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREXSFPM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREXSFPM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STORECGFPM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STORECGFPM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STORECGFPM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREZCDM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREZCDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREZCDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
       
      if @Table='STOREQGADM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREQGADM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREQGADM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end

      if @Table='STOREYunFeiFKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREYunFeiFKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREYunFeiFKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='INVOICEM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from INVOICEM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from INVOICEM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end

      if @Table='STOREZZHPM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREZZHPM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREZZHPM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STORECXHPM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STORECXHPM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STORECXHPM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STORECPJCMBM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STORECPJCMBM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STORECPJCMBM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREPLLLMBM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREPLLLMBM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREPLLLMBM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREZZCXMBM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREZZCXMBM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREZZCXMBM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREDBCKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREDBCKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREDBCKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREDBCKTHM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREDBCKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREDBCKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end

      if @Table='STOREJYCKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREJYCKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREJYCKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREJYCKTHM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREJYCKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREJYCKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREDXRKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREDXRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREDXRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREDXRKTHM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREDXRKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREDXRKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREGJRKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREGJRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREGJRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREGJRKTHM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREGJRKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREGJRKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREDBRKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREDBRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREDBRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREDBRKTHM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREDBRKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREDBRKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREZSRKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREZSRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREZSRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREZSRKTHM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREZSRKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREZSRKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREJYRKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREJYRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREJYRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREJYRKTHM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREJYRKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREJYRKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end

      if @Table='STOREQTRKTHM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREQTRKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREQTRKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STORELiuHM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STORELiuHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STORELiuHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREXSDDM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREXSDDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREXSDDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STORECGDDM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STORECGDDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STORECGDDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STORECGTHM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STORECGTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STORECGTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREXSTHM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREXSTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREXSTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREFYKZM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREFYKZM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREFYKZM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREQTSRM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREQTSRM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREQTSRM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREMOVEM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREMOVEM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREMOVEM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREXSSKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREXSSKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREXSSKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STORECGFKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STORECGFKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STORECGFKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STORECGRKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STORECGRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STORECGRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREXSCKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREXSCKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREXSCKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end

      if @Table='STORELLCKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STORELLCKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STORELLCKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STORECPJCM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STORECPJCM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STORECPJCM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STORECKDBM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STORECKDBM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STORECKDBM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STORECKPDM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STORECKPDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STORECKPDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREHPTJM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREHPTJM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREHPTJM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREHPBSM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREHPBSM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREHPBSM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREQTRKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREQTRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREQTRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end

      if @Table='STOREQTCKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREQTCKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREQTCKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREGJRKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREGJRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREGJRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STORECSHM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STORECSHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STORECSHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREQGDM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREQGDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREQGDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end

      if @Table='STOREJGDM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREJGDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREJGDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end




      set      @idd = rtrim(convert(char,convert(int,@idd)+1))
      set      @bill_no_selfd =@INOUTFlag+'-'+substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)+'-'+substring('0000',1,4-len(@idd))+@idd
end
--------------------------------------------------------------------------------------=====================
if ( @BILLNOFLAG = '0')
begin                                             --------- 入库单号 ---------       


      if @Table='STOREYunFeiFKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREYunFeiFKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREYunFeiFKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end

      if @Table='STORECXHPM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STORECXHPM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STORECXHPM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='INVOICEM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from INVOICEM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from INVOICEM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end

      if @Table='STOREZZHPM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREZZHPM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREZZHPM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREPLLLMBM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREPLLLMBM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREPLLLMBM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STORECPJCMBM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STORECPJCMBM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STORECPJCMBM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREZZCXMBM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREZZCXMBM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREZZCXMBM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREJYCKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREJYCKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREJYCKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREJYCKTHM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREJYCKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREJYCKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREDBCKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREDBCKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREDBCKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREDBCKTHM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREDBCKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREDBCKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREGJRKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREGJRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREGJRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREGJRKTHM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREGJRKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREGJRKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREDXRKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREDXRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREDXRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREDXRKTHM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREDXRKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREDXRKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREDBRKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREDBRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREDBRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREDBRKTHM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREDBRKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREDBRKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREZSRKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREZSRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREZSRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREZSRKTHM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREZSRKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREZSRKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREJYRKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREJYRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREJYRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREJYRKTHM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREJYRKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREJYRKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end

      if @Table='STOREQTRKTHM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREQTRKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREQTRKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STORELiuHM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STORELiuHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STORELiuHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREXSDDM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREXSDDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREXSDDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STORECGDDM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STORECGDDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STORECGDDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STORECGTHM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STORECGTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STORECGTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREXSTHM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREXSTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREXSTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREFYKZM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREFYKZM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREFYKZM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREQTSRM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREQTSRM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREQTSRM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREMOVEM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREMOVEM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREMOVEM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREXSSKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREXSSKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREXSSKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STORECGFKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STORECGFKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STORECGFKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STORECGRKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STORECGRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STORECGRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end

      if @Table='STOREXSCKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREXSCKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREXSCKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end

      if @Table='STORELLCKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STORELLCKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STORELLCKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end

      if @Table='STORECPJCM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STORECPJCM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STORECPJCM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end

      if @Table='STORECKDBM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STORECKDBM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STORECKDBM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STORECKPDM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STORECKPDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STORECKPDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end

      if @Table='STOREHPTJM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREHPTJM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREHPTJM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREHPBSM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREHPBSM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREHPBSM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREQTRKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREQTRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREQTRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end

      if @Table='STOREQTCKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREQTCKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREQTCKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREGJRKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREGJRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREGJRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STORECSHM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STORECSHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STORECSHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end

      if @Table='STOREJGDM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREJGDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREJGDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREQGDM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREQGDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREQGDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end

      if @Table='STOREQGADM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREQGADM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREQGADM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end

      if @Table='STOREZCDM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREZCDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREZCDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREXSFPM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREXSFPM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREXSFPM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STORECGFPM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STORECGFPM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STORECGFPM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end

      if @Table='STOREZFDM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREZFDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREZFDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end


      set      @idd = rtrim(convert(char,convert(int,@idd)+1))
      set      @bill_no_selfd =@INOUTFlag+'-'+@sysdate+'-'+substring('0000',1,4-len(@idd))+@idd
end


end















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG

















--------------------------------------------------------------------

CREATE PROCEDURE GET_CURR_YYYYMM_FlagPost  
AS                 
declare @YYYYMM varchar(6)                   --会计年月     

declare @MINBILLDATE DATEtime
declare @MAXBILLDATE DATEtime
declare @PRODUCTDATE DATEtime
declare @B_ID INTEGER
declare @STOREHSFS   INTEGER

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           


   declare  @PREV_YYYYMM          varchar(6)  -- 上一个会计年月
   declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
	if substring(@YYYYMM,5,2) = '12'  --- 如果当前会计月等于最大的会计月，将需要转入下年的的第一个会计年月
	begin
	    set @Next_YYYYMM   = convert(varchar,convert(int,substring(@YYYYMM,1,4))+1) +'01'  
	end
	else
	begin
	    set @Next_YYYYMM   = substring(@YYYYMM,1,4) +substring('00',1,2-len(convert(varchar,convert(int,substring(@YYYYMM,5,2))+1)))+convert(varchar,convert(int,substring(@YYYYMM,5,2))+1)
	end

	if substring(@YYYYMM,5,2) = '01'  --- 如果当前会计月等于最大的会计月，将需要转入下年的的第一个会计年月
	begin
	    set @PREV_YYYYMM   = convert(varchar,convert(int,substring(@YYYYMM,1,4))-1) +'12'  
	end
	else
	begin
	    set @PREV_YYYYMM   = substring(@YYYYMM,1,4) +substring('00',1,2-len(convert(varchar,convert(int,substring(@YYYYMM,5,2))-1)))+convert(varchar,convert(int,substring(@YYYYMM,5,2))-1)
	end

	declare @YYYYMMFS INTEGER
	declare @YYYYMMFSDATE  INTEGER
	declare @Billday  INTEGER

	       SELECT    @YYYYMMFS =(SELECT  YYYYMMFS   FROM   ACCINFO    WHERE   GUID='0001' )    
                IF @YYYYMMFS=1
	  BEGIN
		     SET  @MINBillDate = CONVERT(DATEtime,@YYYYMM+'01')
		     SET  @MAXBillDate =CONVERT(DATEtime,@Next_YYYYMM+'01')

	  END
               ELSE
               BEGIN
	       SELECT    @YYYYMMFSDATE =(SELECT  YYYYMMFSDATE   FROM   ACCINFO    WHERE   GUID='0001' )    
       
	     SET  @MINBillDate =DATEADD(day, @YYYYMMFSDATE, CONVERT(DATEtime,@PREV_YYYYMM+'01'))
	     SET  @MAXBillDate =DATEADD(day, @YYYYMMFSDATE, CONVERT(DATEtime,@YYYYMM+'01'))



	 END

          select DISTINCT CODE ,BILLDATE from VIEWBILL WHERE FLAGPOST = 0  and BILLdate >= @MINBillDate and BILLdate <@MAXBillDate





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG





--------------------------------------------------------------------

---此过程取得单据的标识   ID
---此过程取得单据的标识   ID 为8位字符串

CREATE PROCEDURE [dbo].[GET_CWPZ_BILLID] (@R_KeyValue VARCHAR(20)  output)    --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 
  declare @curKeyValue VARCHAR(20)
  declare @NextKeyValue VARCHAR(20)
  declare @BILLID VARCHAR(20)
  declare @YYYYMM varchar(6)                   --会计年月     

BEGIN
--- 	 set @curkeyvalue='00000000'
          set @YYYYMM   = (select optionvalue from accoptions where optionname ='CW_YYYYMM')     

	  select @curkeyvalue=Substring(BILLID,7,6) from CW_PingZhengM   where Substring(BILLID,1,6)=@YYYYMM

          set @NextKeyValue = rtrim(convert(char,convert(int,@curkeyvalue)+1))
          set @NextKeyValue = substring('000000',1,6-len(@NextKeyValue))+@NextKeyValue

	  if (@curkeyvalue  is NULL)  or (not (len(@curkeyvalue)=6 ) )
	  begin
	    set @R_KeyValue=@YYYYMM+'000001'
	  end
	  else
	  begin
	    set @R_KeyValue =@YYYYMM+@NextKeyValue
	  end
END
  





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG








--------------------------------------------------------------------

---此过程功能试算平衡

CREATE PROCEDURE [dbo].[GET_CW_initbala_PingHeng] (@Debit_LeiJi t_amount  output,@Credit_LeiJi t_amount  output,
        @Balance_Jie t_amount  output,   @YearBalance_Jie t_amount  output,
        @Balance_Dai t_amount  output,   @YearBalance_Dai t_amount  output,
	 @PingHengFlag int   output)
AS 
 
  declare @curKeyValue VARCHAR(20)
  declare @NextKeyValue VARCHAR(20)
  declare @YYYYMM varchar(6)                   --会计年月     
  declare @MAXBILLDATE DATEtime 
  declare @MINBILLDATE DATEtime 
  declare @PLHaveDone_Jie t_amount
  declare @PLHaveDone_Dai t_amount

BEGIN

	set @PingHengFlag=1   ---为平衡

SELECT @Debit_LeiJi=SUM(Debit) ,@Credit_LeiJi=SUM(Credit)  FROM  CW_INITBALA


SELECT @Balance_Jie=SUM(Balance) , @PLHaveDone_Jie=SUM(PLHaveDone)    FROM  CW_INITBALA

where dcflag=1
set @YearBalance_Jie=@Balance_Jie-@Debit_LeiJi+@Credit_LeiJi

SELECT @Balance_Dai=SUM(Balance) , @PLHaveDone_Dai=SUM(PLHaveDone)    FROM  CW_INITBALA

where dcflag=-1

set @YearBalance_Dai=@Balance_Dai-@Debit_LeiJi+@Credit_LeiJi

	if @Debit_LeiJi<>@Credit_LeiJi OR @Balance_Jie<>@Balance_Dai OR @YearBalance_Jie<>@YearBalance_Dai
	begin
	set @PingHengFlag=0   ---不平衡
	end




END
  








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG






--------------------------------------------------------------------

---此过程取得单据的标识   ID
---此过程取得单据的标识   ID 为8位字符串

CREATE PROCEDURE [dbo].[GET_Cred_Code_NO] (@CredTypeID int ,@CredNo int  output,@CredCode int  output)    --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 
  declare @curKeyValue VARCHAR(20)
  declare @NextKeyValue VARCHAR(20)
  declare @BILLID VARCHAR(20)
  declare @MAXBILLDATE DATEtime 
  declare @MINBILLDATE DATEtime 

BEGIN
--- 	 set @curkeyvalue='00000000'

		exec Get_Max_Min_Date @MAXBILLDATE output,@MINBILLDATE output


	  select @CredNo=Max(CredNo)  from CW_PingZhengM   where BILLDate >=@MINBILLDATE AND BILLDate < @MAXBILLDATE

	  if (@CredNo  is NULL)  
	  begin
	    set @CredNo=1
	  end
	  else
	  begin
	    set @CredNo=@CredNo+1
	  end

	  select @CredCode=Max(CredCode)  from CW_PingZhengM   where BILLDate >=@MINBILLDATE AND BILLDate < @MAXBILLDATE AND CredTypeID=@CredTypeID

	  if (@CredCode  is NULL)  
	  begin
	    set @CredCode=1
	  end
	  else
	  begin
	    set @CredCode=@CredCode+1
	  end






END


----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











----------------------------------------------------------------------------
CREATE PROCEDURE [GET_EPRICE ]  (  @GOODSID varchar(22),      ---单据编号   
	     @STOREID varchar(22),  
	@EPRICE NUMERIC(20,10)   output)     --APSOFTENCRYPTION       WITH ENCRYPTION
AS 


declare @STOREHSFS   INTEGER
declare @MAXID   varchar(30)
declare @MAXbilldate  datetime   
 
BEGIN



	       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )      

                     SELECT   @EPRICE=0.00 

                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN

	                           select @MAXBILLDATE=MAX(BILLDATE) FROM detailbillflow   WHERE  GOODSID=@GOODSID  AND   STOREID=@STOREID    AND YYYYMMBILL=1
	                           SELECT  @MAXID=MAX(ID)  FROM detailbillflow  WHERE  GOODSID=@GOODSID  AND   STOREID=@STOREID   AND  BILLDATE=@MAXBILLDATE    AND YYYYMMBILL=1   
		                 SELECT  @EPRICE =EPRICE    FROM DETAILBILLFLOW  WHERE GOODSID = @GOODSID  AND STOREID=@STOREID  AND ID=@MAXID
                            END
                            IF   @STOREHSFS=0
                            BEGIN
	                            select @MAXBILLDATE=MAX(BILLDATE) FROM detailbillflow   WHERE  GOODSID=@GOODSID     AND YYYYMMBILL=1
	                            SELECT  @MAXID=MAX(ID)  FROM detailbillflow  WHERE  GOODSID=@GOODSID   AND  BILLDATE=@MAXBILLDATE    AND YYYYMMBILL=1   
		                 SELECT  @EPRICE = EPRICE    FROM DETAILBILLFLOW   WHERE GOODSID = @GOODSID  AND ID=@MAXID
                            END

END





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












------------------

CREATE PROCEDURE [dbo].[GET_GoodsTypeNew_PrevNO] (
                  @Lcode varchar(50),
                  @PrevNO varchar(50) output, --单号
                  @ReturnFlag  int output --单号
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --当前会计年月     
declare @idd varchar(50)
declare @HouBuidd varchar(50)                     --序列号
declare @BILLNOFLAG  varchar(1)                     --单据格式
declare @BILLW  varchar(20)                     --单据格式
declare @YYYYMM_FLAG  INTEGER
declare @TempSTR varchar(2000)
declare @MM int

begin

	     Set  @MM= CHARINDEX('.',@LCODE)

	     if @MM=0 
	     begin
	             SET @PrevNO='00' 
	     end	
	     else
	     begin

		     SET @PrevNO=''
		     SET @TempSTR=@Lcode
		     while @MM>0 
		     begin
			 IF @PrevNO=''
			 begin
			 SET @PrevNO=SubString(@TempSTR,1,@MM-1)
			 end
			 ELse
			 begin
			 SET @PrevNO=@PrevNO+'.'+SubString(@TempSTR,1,@MM-1)
			 end
		
		         SET @TempSTR=SubString(@TempSTR,@MM+1,Len(@TempSTR)-@MM)
			 Set @MM= CHARINDEX('.',@TempSTR)

		     end

	     end

             IF exists(select * from GoodstypeNew where LCODE=@PrevNO)
	     begin

		If exists(select * from GoodstypeNew where LCODE=@LCODE)
		begin
		set @ReturnFlag=0
		end
		else
		begin
		set @ReturnFlag=1
		end
	     end
	     else
	     begin
		set @ReturnFlag=0
	     end



end






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











------------------

CREATE PROCEDURE [dbo].[GET_ItemInfo_ItemBM] (
                  @PrevNO varchar(50),
                  @bill_no_selfd varchar(50) output --单号
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --当前会计年月     
declare @idd varchar(50)
declare @HouBuidd varchar(50)                     --序列号
declare @BILLNOFLAG  varchar(1)                     --单据格式
declare @BILLW  varchar(20)                     --单据格式
declare @YYYYMM_FLAG  INTEGER
begin

---      select   @idd = (select max(substring(ItemBM,len(@PrevNO)+1,len(ItemBM)-len(@PrevNO))) as maxid from ItemInfo where PrevNO=@PrevNO)

	if @PrevNO='0000'
	begin
	      set  @bill_no_selfd =''
		return
	end

      select   @idd = (select max(ItemBM) as maxid from ItemInfo where PrevNO=@PrevNO)
--      select   @idd = (select max(substring(CODE,12,4)) as maxid from STOREZZHPM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
	set @HouBuIdd='1'+substring(@idd,len(@PrevNO)+1,len(@idd)-len(@PrevNO))

      set      @HouBuIdd = rtrim(convert(char,convert(int,@HouBuIdd)+1))
		
      set      @bill_no_selfd =substring(@HouBuidd,2,len(@HouBuidd)-1)

end





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














CREATE PROCEDURE GET_MQTY_EQTY_2011(@GOODSID  varchar(20)  ,         ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
					@STOREID varchar(8) ,                        -----如果为0000则全部仓库
						           @MEQTY   NUMERIC(20,10)    OUTPUT,
						           @EQTY   NUMERIC(20,10)    OUTPUT
                         
                                                      )   --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @YYYYMM  varchar(8),      --------为当前会计期间
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000)
Declare    @STOREIDSTR   varchar(80)

set @temp_year  = convert(varchar,year(getdate()))
set @temp_month = substring('00',1,2-len(convert(varchar,month(getdate()))))+convert(varchar,month(getdate()))
set @temp_day   = substring('00',1,2-len(convert(varchar,day(getdate()))))+convert(varchar,day(getdate()))
set @now_date   = @temp_year + @temp_month +@temp_day

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')    

		 IF   @STOREID='0000'
		BEGIN
		 SET @STOREIDSTR = '    '
		END
		ELSE
		BEGIN
		 SET @STOREIDSTR = '  AND   STOREID = '+char(39)+ @STOREID+char(39)
		END
 



----------------------------------------------------
		SELECT @SQLSTR='	INSERT  #GOODSTEMP      select  I.GOODSID,       '
		SELECT @SQLSTR=@SQLSTR+'  ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0)  as MEQTY, '   --期末数量
		SELECT @SQLSTR=@SQLSTR+'  ISNULL(B.BQTY,0)+ isnull(E.INQTY,0)  as EQTY   '   --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from Goods    AS  I'
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(INQTY*INOUTFLAG)  as INQTY  ,sum(MINQTY*INOUTFLAG)  as MINQTY '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)+@STOREIDSTR                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(BQTY) as BQTY ,sum(MBQTY) as MBQTY'
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39)+@STOREIDSTR 
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where    I.GOODSID   = ' +char(39)+@GOODSID+char(39)
------------------------------------------------------------------------
Create Table #GOODSTEMP
      (   GOODSID  nvarchar(50)  NULL,
	[MEQTY] NUMERIC(20,10)  NULL ,
	[EQTY] NUMERIC(20,10)  NULL 
		)

 		EXEC(@SQLSTR)
                      SELECT  @EQTY=(SELECT isnull(EQTY,0)  AS  EQTY  FROM #GOODSTEMP )
                      SELECT  @MEQTY=(SELECT isnull(MEQTY,0)  AS  MEQTY  FROM #GOODSTEMP )








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












--------------------------------------------------------------------

---此过程解决取五笔和拼音码的首字符

CREATE PROCEDURE [GETwb_py_FIRST] ( @INPUTSTRING   VARCHAR(200) ,  @PY_STRING  VARCHAR(200) output,@WB_STRING  VARCHAR(200)  output)    --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 
  declare @WBTMPSTR  VARCHAR(20)
  declare @PYTMPSTR  VARCHAR(20)
  declare @WBTMPSTR00  VARCHAR(200)
  declare @PYTMPSTR00  VARCHAR(200)
  declare @M  INT

BEGIN
  
	SET @M=LEN(@INPUTSTRING)
	  set @WB_STRING = ''

	  set @PY_STRING = ''

	  set @WBTMPSTR00 = ''

	  set @PYTMPSTR00 = ''

	WHILE @M  > 0
	BEGIN
		  SELECT @WBTMPSTR=SUBSTRING(WB,1,1)  FROM CHINESE  WHERE  SUBSTRING(@INPUTSTRING,@M,1) = HANZI
		  SELECT @PYTMPSTR=SUBSTRING(PY,1,1)  FROM CHINESE  WHERE  SUBSTRING(@INPUTSTRING,@M,1) = HANZI

		  set @WBTMPSTR00 =ISNULL(@WBTMPSTR,'')+@WBTMPSTR00

		  set @PYTMPSTR00 =ISNULL(@PYTMPSTR,'')+@PYTMPSTR00
		                                    
		     SET @M=@M-1
	 END

	  set @WB_STRING = @WBTMPSTR00

	  set @PY_STRING =  @PYTMPSTR00




END





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG






--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE [dbo].[GOODSCGDDMXB]( @WHERESTING   varchar(1800)
                       
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8)

declare @VENDORNAME  varchar(50)
declare @GOODSNAME  varchar(50)

declare @ID  nvarchar(50)
declare @VENDORID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @VENDORCODE  nvarchar(50)
declare @GOODSCODE  nvarchar(50)
declare @SPECNAME nvarchar(50)
declare @MODELNAME nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLCODE  nvarchar(50)
declare @BILLTYPE INT
declare @BILLDATE  datetime
declare @GOODSID00  nvarchar(50)
declare @PRICE NUMERIC(20, 6)
declare @TAXAMT NUMERIC(20, 2)
declare @WCunitQTY NUMERIC(20, 6)
declare @WCquantity NUMERIC(20, 6)
declare @zzunitQTY NUMERIC(20, 6)
declare @zzquantity NUMERIC(20, 6)
declare @WCTAXAMT NUMERIC(20, 6)
declare @TAXRATE  NUMERIC(20, 6)
declare @RATE  NUMERIC(20, 6)
declare @WEITAXAMT NUMERIC(20, 6)
declare @SUMWCTAXAMT NUMERIC(20, 6)
declare @SUMWEITAXAMT NUMERIC(20, 6)
declare @SUMTAXAMT NUMERIC(20, 6)
declare @UNITQTY NUMERIC(20, 6)
declare @quantity NUMERIC(20, 6)
declare @UNITPRICE NUMERIC(20, 6)
declare @DISC NUMERIC(20, 6)
declare    @PRICETYPE int

Create Table #temptable1
      (   GOODSID varchar(50)  NULL,
       VENDORID  varchar(10) ,
       VENDORCODE  varchar(30) ,
      BILLID  nvarchar(50)  NULL,
      BILLTYPE  INT ,
	[PRICE] NUMERIC(20, 6)  NULL ,
	[UNITQTY] NUMERIC(20, 6)  NULL ,
	[quantity] NUMERIC(20, 6)  NULL ,
	[DISC] NUMERIC(20, 6)  NULL ,
	[TAXRATE]NUMERIC(20, 6)  NULL ,
	   BILLDATE  datetime  NULL,
	[UNITPRICE] NUMERIC(20, 6)  NULL ,
	[WCunitQTY]NUMERIC(20, 6)  NULL ,
	[WCquantity]NUMERIC(20, 6)  NULL ,
	[zzunitQTY]NUMERIC(20, 6)  NULL ,
	[zzquantity]NUMERIC(20, 6)  NULL ,
	[TAXAMT]NUMERIC(20, 2)  NULL, 
	[PRICETYPE]    int  NULL, 
	       DETAILBILLFLOWID  varchar(10) 
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   VIEWCGDD.GOODSID,VIEWCGDD.VENDORID,VENDOR.CODE AS VENDORCODE, BILLID,BILLTYPE,PRICE,UNITQTY,quantity,DISC,TAXRATE,BILLDATE '
           SELECT  @SQLSTR = @SQLSTR+' ,UNITPRICE,WCunitQTY,WCquantity,zzunitQTY,zzquantity,TAXAMT,PRICETYPE,DETAILBILLFLOWID  from VIEWCGDD   ,VENDOR  '  + @WHERESTING +'  AND  VIEWCGDD.VENDORID = VENDOR.VENDORID'
           SELECT  @SQLSTR = @SQLSTR+'  order by VIEWCGDD.GOODSID,VIEWCGDD.VENDORID,BILLDATE,DETAILBILLFLOWID '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
	   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   VENDORNAME  nvarchar(50)  NULL,
   VENDORCODE  nvarchar(50)  NULL,
   UNIT  nvarchar(10)  NULL,
	[UNITQTY] NUMERIC(20, 6)  NULL ,
	[quantity] NUMERIC(20, 6)  NULL ,
	[TAXAMT]NUMERIC(20, 2)  NULL, 
	[WCunitQTY] NUMERIC(20, 6)  NULL ,
	[WCquantity] NUMERIC(20, 6)  NULL ,
	[zzunitQTY] NUMERIC(20, 6)  NULL ,
	[zzquantity] NUMERIC(20, 6)  NULL ,
	[WCTAXAMT]NUMERIC(20, 6)  NULL ,
	[WEIunitQTY] NUMERIC(20, 6)  NULL ,
	[WEIquantity] NUMERIC(20, 6)  NULL ,
	[WEITAXAMT]NUMERIC(20, 6)  NULL 
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (select  GOODSID, VENDORID, BILLID,PRICE,UNITQTY,TAXRATE,BILLTYPE   from  #temptable1        )
                 begin
	    declare CGDDMXB_GOODS Cursor for select  GOODSID, VENDORID, BILLID,PRICE,UNITQTY,quantity,TAXRATE,BILLTYPE ,DISC,UNITPRICE,WCunitQTY,WCquantity, zzunitQTY,zzquantity,TAXAMT,PRICETYPE  from  #temptable1  
---                                                            ORDER BY  GOODSID,  BILLDATE,DETAILBILLFLOWID,VENDORCODE
                                                            ORDER BY  GOODSID,  BILLDATE,BILLID,VENDORCODE
	    Open CGDDMXB_GOODS

	    fetch CGDDMXB_GOODS into   @GOODSID,@VENDORID,@BILLID,@PRICE,@UNITQTY,@quantity,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@WCunitQTY,@WCquantity,@zzunitQTY,@zzquantity,@TAXAMT,@PRICETYPE

                 SELECT  @VENDORNAME =(SELECT NAME   FROM VENDOR  WHERE VENDORID=@VENDORID)
                 SELECT  @VENDORCODE =(SELECT CODE  FROM VENDOR  WHERE VENDORID=@VENDORID)
                 SELECT  @GOODSCODE=CODE,@GOODSNAME=Name,@SpecName=SpecName,@ModelName=ModelName     FROM GOODS  WHERE GOODSID=@GOODSID
                 SELECT  @GOODSNAME =@GOODSNAME+' '+ISNULL(@SpecName,'')+' '+ISNULL(@ModelName,'')
                 SELECT  @GOODSCODE='钢材编码：'+@GOODSCODE

                 SELECT  @GOODSID00=@GOODSID

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,VENDORNAME         )
                                           VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
		SELECT @SUMWCTAXAMT=0
		SELECT @SUMTAXAMT=0
		SELECT @SUMWEITAXAMT=0
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF  not( @GOODSID00 = @GOODSID)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,WCTAXAMT,TAXAMT,WEITAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMWCTAXAMT,@SUMTAXAMT,@SUMWEITAXAMT)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

		                 SELECT  @VENDORNAME =(SELECT NAME   FROM VENDOR  WHERE VENDORID=@VENDORID)
		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @VENDORCODE =(SELECT CODE  FROM VENDOR  WHERE VENDORID=@VENDORID)
                 SELECT  @GOODSCODE=CODE,@GOODSNAME=Name,@SpecName=SpecName,@ModelName=ModelName     FROM GOODS  WHERE GOODSID=@GOODSID
                 SELECT  @GOODSNAME =@GOODSNAME+' '+ISNULL(@SpecName,'')+' '+ISNULL(@ModelName,'')
                 SELECT  @GOODSCODE='钢材编码：'+@GOODSCODE
		                 
		                 SELECT  @GOODSID00=@GOODSID


			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,VENDORNAME         )
                                           VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
				SELECT @SUMWCTAXAMT=0
				SELECT @SUMTAXAMT=0
				SELECT @SUMWEITAXAMT=0
		END	
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

				--SELECT @RATE =RATE  FROM VENDORUNIT  WHERE VENDORID=@VENDORID AND UNITID=@UNITID

			SELECT @UNIT = UNIT   FROM GOODS  WHERE GOODSID=@GOODSID
				
			   SELECT @BILLCODE=(SELECT CODE   FROM STORECGDDM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STORECGDDM  WHERE BILLID=@BILLID)
		                 SELECT  @VENDORNAME=(SELECT NAME   FROM VENDOR  WHERE VENDORID=@VENDORID)
		                 SELECT  @VENDORCODE=(SELECT CODE   FROM VENDOR  WHERE VENDORID=@VENDORID)
		               if @PRICETYPE=1
		               begin  
		                 SET @WEITAXAMT=Round(ISNULL(@DISC,100)*0.01*(ISNULL(@quantity,0)-ISNULL(@WCquantity,0)-ISNULL(@zzquantity,0))*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
		                 SET @WCTAXAMT=Round(ISNULL(@DISC,100)*0.01*ISNULL(@WCquantity,0)*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
					   end
					   else
					   begin
		                 SET @WEITAXAMT=Round(ISNULL(@DISC,100)*0.01*(ISNULL(@unitqty,0)-ISNULL(@WCunitqty,0)-ISNULL(@zzunitqty,0))*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
		                 SET @WCTAXAMT=Round(ISNULL(@DISC,100)*0.01*ISNULL(@WCunitqty,0)*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
					   end
		                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,VENDORNAME,VENDORCODE,UNIT, UNITQTY,quantity,TAXAMT,WCunitQTY,WCquantity,zzunitQTY,zzquantity,WCTAXAMT,WEIunitQTY,WEIquantity,WEITAXAMT)
             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@VENDORNAME,@VENDORCODE,@UNIT,@UNITQTY,@quantity,
					                     @TAXAMT,
					                     ISNULL(@WCunitQTY,0) ,
					                     ISNULL(@WCquantity,0) ,
					                     ISNULL(@zzunitQTY,0) ,
					                     ISNULL(@zzquantity,0) ,					@WCTAXAMT,
					                      @UNITQTY-ISNULL(@WCunitQTY,0) -ISNULL(@zzunitQTY,0),
					                      @quantity-ISNULL(@WCquantity,0) -ISNULL(@zzquantity,0),@WEITAXAMT	)

				SELECT @SUMTAXAMT=@SUMTAXAMT+@TAXAMT
				SELECT @SUMWCTAXAMT=@SUMWCTAXAMT+@WCTAXAMT
				SELECT @SUMWEITAXAMT=@SUMWEITAXAMT+@WEITAXAMT
		
	    fetch CGDDMXB_GOODS into   @GOODSID,@VENDORID,@BILLID,@PRICE,@UNITQTY,@quantity,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@WCunitQTY,@WCquantity,@zzunitQTY,@zzquantity,@TAXAMT,@PRICETYPE
 
	    END           ------- CGDDMXB_GOODS  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,WCTAXAMT,TAXAMT,WEITAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMWCTAXAMT,@SUMTAXAMT,@SUMWEITAXAMT)

	    close CGDDMXB_GOODS
	    deallocate CGDDMXB_GOODS
        end     ------------  if exists

 SELECT *  FROM #temptable2         ORDER BY ID











----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG

















--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE GOODSCGRKMXB( @WHERESTING   varchar(1800)
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8)

declare @VENDORNAME  varchar(50)

declare @ID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @VENDORID  nvarchar(50)
declare @GOODSNAME  nvarchar(50)
declare @GOODSCODE  nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLTYPE  INT
declare @PRICETYPE  INT
declare @BILLCODE  nvarchar(50)
declare @BILLDATE  datetime
declare @GOODSID00  nvarchar(50)
declare @PRICE NUMERIC(20,10)
declare @QUANTITY NUMERIC(20,10)
declare @TAXRATE  NUMERIC(20,10)
declare @SUMAMT NUMERIC(20,10)
declare @UNITPRICE  NUMERIC(20,10)
declare @UNITQTY NUMERIC(20,10)
declare @FuZhuQTY varchar(50)
declare @DISC NUMERIC(20,10)
declare @SUMTAXAMT NUMERIC(20,10)
declare @AMT NUMERIC(20,10)
declare @TAXAMT NUMERIC(20,10)
declare @VendorFlag smallint 
declare @DunQTY NUMERIC(20,10)
declare @Rate NUMERIC(20,10)
declare @SumDunQTY NUMERIC(20,10)
    

Create Table #temptable1
      (GOODSID  varchar(10) ,
             goodscode  nvarchar(50)  NULL,
             BILLID  nvarchar(50)  NULL,
             BILLTYPE  INT,
	[PRICE] NUMERIC(20,10)  NULL ,
	[QUANTITY] NUMERIC(20,10)  NULL ,
	[TAXRATE]NUMERIC(20,10)  NULL ,
	[DISC]NUMERIC(20,10)  NULL ,
	BILLDATE DATEtime,
	[UNITPRICE] NUMERIC(20,10)  NULL ,
	[UNITQTY]NUMERIC(20,10)  NULL ,
	FuZhuQTY varchar(50)  NULL,
		     PRICETYPE  INT ,
	[AMT]NUMERIC(20,10)  NULL ,
	[TAXAMT]NUMERIC(20,10)  NULL, 
	[VendorFlag]smallint  NULL 
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   VIEWCGRK.GOODSID,GOODS.CODE AS GOODSCODE, BILLID,BILLTYPE,VIEWCGRK.PRICE,QUANTITY,TAXRATE,DISC,BILLDATE '
           SELECT  @SQLSTR = @SQLSTR+' , UNITPRICE ,UNITQTY,FuZhuQTY,PRICETYPE,AMT,TAXAMT,VendorFlag  from VIEWCGRK   ,GOODS    '  + @WHERESTING +'  AND  VIEWCGRK.GOODSID = GOODS.GOODSID'
           SELECT  @SQLSTR = @SQLSTR+'  order by  VIEWCGRK.GOODSID,BILLDATE,BILLID '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   VENDORNAME  nvarchar(50)  NULL,
   UNIT  nvarchar(10)  NULL,
	[QUANTITY] NUMERIC(20,10)  NULL ,
	[PRICE] NUMERIC(20,10)  NULL ,
	[TAXRATE]NUMERIC(20,10)  NULL ,
	[AMT]NUMERIC(20,10)  NULL ,
	[TAXAMT]NUMERIC(20,10)  NULL ,
	 PRICETYPENAME  nvarchar(10)  NULL,
	FuZhuQTY varchar(50)  NULL,
	[DunQTY]NUMERIC(20,10)  NULL 
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (select   GOODSID, BILLID,PRICE,QUANTITY,TAXRATE   from  #temptable1        )
                 begin
	    declare CGRKMXB_CRGR Cursor for select   GOODSID, BILLID,PRICE,QUANTITY,FuZhuQTY,TAXRATE,BILLTYPE,DISC,UNITPRICE ,UNITQTY ,PRICETYPE,AMT,TAXAMT,VendorFlag  from  #temptable1  
                                                            ORDER BY  GOODSID,BILLDATE, BILLID
	    Open CGRKMXB_CRGR

	    fetch CGRKMXB_CRGR into   @GOODSID,@BILLID,@PRICE,@QUANTITY,@FuZhuQTY,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE ,@UNITQTY  ,@PRICETYPE, @AMT,@TAXAMT,@VendorFlag

                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @GOODSCODE='商品编码：'+@GOODSCODE
                 SELECT  @GOODSID00=@GOODSID

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,VENDORNAME         )
                                           VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
		SELECT @SUMAMT=0
		SELECT @SUMTAXAMT=0
		SELECT @SUMDunQTY=0
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF  not( @GOODSID00 = @GOODSID)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,AMT,TAXAMT,DunQTY)
                                           VALUES  (@COUNTID, '小计',@SUMAMT,@SUMTAXAMT,@SumDunQTY)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @GOODSCODE='商品编码：'+@GOODSCODE
		                 SELECT  @GOODSID00=@GOODSID

			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                          INSERT    INTO   #temptable2  (ID, BILLCODE,VENDORNAME    )
                           	                VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
				SELECT @SUMAMT=0
				SELECT @SUMTAXAMT=0
				SELECT @SUMDunQTY=0
		END	
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	  			SELECT @UNIT = (SELECT UNIT   FROM GOODS  WHERE GOODSID=@GOODSID)

			   IF @BILLTYPE=1
			  BEGIN
			   SELECT @BILLCODE=(SELECT CODE   FROM STORECGRKM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STORECGRKM  WHERE BILLID=@BILLID)
			   SELECT @VENDORID=(SELECT VENDORID   FROM STORECGRKM  WHERE BILLID=@BILLID)
			  END
			   IF @BILLTYPE=7
			  BEGIN
			   SELECT @BILLCODE=(SELECT CODE   FROM STORECGTHM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STORECGTHM  WHERE BILLID=@BILLID)
			   SELECT @VENDORID=(SELECT VENDORID   FROM STORECGTHM  WHERE BILLID=@BILLID)
			  END
		                 SELECT  @VENDORNAME =(SELECT NAME   FROM ViewVENDOR  WHERE VENDORID=@VENDORID  and VendorFlag=@VendorFlag)

				IF @PRICETYPE=1 
				BEGIN
			                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,VENDORNAME,UNIT, QUANTITY,FuZhuQTY,PRICE,TAXRATE, AMT,TAXAMT,PRICETYPENAME,DunQTY)
             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@VENDORNAME,@UNIT,@UNITQTY,@FuZhuQTY,@UNITPRICE,@TAXRATE,@AMT,@TAXAMT,'重量',@QUANTITY)
					
					set @DunQTY=@QUANTITY
				END
				IF @PRICETYPE=0
				BEGIN
		                 SELECT  @Rate =(SELECT ISNULL(Rate,0) FROM GOODS  WHERE GOODSID=@GOODSID)

			                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,VENDORNAME,UNIT, QUANTITY,FuZhuQTY,PRICE,TAXRATE, AMT,TAXAMT,PRICETYPENAME,DunQTY)
             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@VENDORNAME,@UNIT,@UNITQTY,@FuZhuQTY,@UNITPRICE,@TAXRATE,@AMT,@TAXAMT,'数量',@Rate*@UNITQTY)
					set @DunQTY=@Rate*@UNITQTY
				END

				SELECT @SUMAMT=@SUMAMT+@AMT
				SELECT @SUMTAXAMT=@SUMTAXAMT+@TAXAMT
				SELECT @SUMDunQTY=@SUMDunQTY+@DunQTY
		
	    fetch CGRKMXB_CRGR into   @GOODSID,@BILLID,@PRICE,@QUANTITY,@FuZhuQTY,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE ,@UNITQTY  ,@PRICETYPE, @AMT,@TAXAMT,@VendorFlag
 
	    END           ------- CGRKMXB_CRGR  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,AMT,TAXAMT,DunQTY)
                                           VALUES  (@COUNTID, '小计',@SUMAMT,@SUMTAXAMT,@SUMDunQTY)

	    close CGRKMXB_CRGR
	    deallocate CGRKMXB_CRGR
        end     ------------  if exists

 SELECT *  FROM #temptable2         ORDER BY ID








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG








------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE GOODSGJRKMXB( 
				@BEGINDATE   varchar(18),
				@ENDDATE   varchar(18),
				@WHERESTING   varchar(1800)
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8)

declare @VENDORNAME  varchar(50)

declare @ID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @VENDORID  nvarchar(50)
declare @GOODSNAME  nvarchar(50)
declare @GOODSCODE  nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLTYPE  INT
declare @BILLCODE  nvarchar(50)
declare @BILLDATE  datetime
declare @GOODSID00  nvarchar(50)
declare @PRICE NUMERIC(20,10)
declare @QTY NUMERIC(20,10)
declare @AMT NUMERIC(20,10)
declare @QUANTITY NUMERIC(20,10)
declare @SUMAMT NUMERIC(20,10)
declare @UNITPRICE  NUMERIC(20,10)
declare @UNITQTY NUMERIC(20,10)
declare @SUMQTY NUMERIC(20,10)
    

Create Table #temptable1
      (GOODSID  varchar(10) ,
             goodscode  nvarchar(50)  NULL,
             BILLID  nvarchar(50)  NULL,
             BILLTYPE  INT,
	[PRICE] NUMERIC(20,10)  NULL ,
	[QUANTITY] NUMERIC(20,10)  NULL ,
	[TAXRATE]NUMERIC(20,10)  NULL ,
	[DISC]NUMERIC(20,10)  NULL ,
	BILLDATE DATEtime,
	[UNITPRICE] NUMERIC(20,10)  NULL ,
	[UNITQTY]NUMERIC(20,10)  NULL 
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   VIEWGJRK.GOODSID,GOODS.CODE AS GOODSCODE, BILLID,BILLTYPE,VIEWGJRK.PRICE,QUANTITY,TAXRATE,DISC,BILLDATE '
           SELECT  @SQLSTR = @SQLSTR+' , UNITPRICE ,UNITQTY   from VIEWGJRK   ,GOODS    '  + @WHERESTING +'  AND  VIEWGJRK.GOODSID = GOODS.GOODSID '
           SELECT  @SQLSTR = @SQLSTR+'   AND   BILLDATE <= '+CHAR(39)+@ENDDATE +CHAR(39) +' AND   BILLDATE >= '+CHAR(39)+@BEGINDATE+CHAR(39)
           SELECT  @SQLSTR = @SQLSTR+'   order by  VIEWGJRK.GOODSID,BILLDATE,BILLID '  
            EXEC( @SQLSTR)

Create Table #temptable10
      (GOODSID  varchar(10) ,
	[QTY] NUMERIC(20,10)  NULL ,
	[AMT] NUMERIC(20,10)  NULL 
		)

-----------------------------------------这个地方应该为合计数

           SELECT  @SQLSTR = ' INSERT #temptable10  '
           SELECT  @SQLSTR = @SQLSTR+' select   VIEWGJRK.GOODSID, SUM(ISNULL(QUANTITY,0))  AS QTY '
           SELECT  @SQLSTR = @SQLSTR+' , SUM(UNITPRICE*(isnull(quantity,0)-ISNULL(RETURNQTY,0)))  AS AMT      from VIEWGJRK   ,GOODS    '  + @WHERESTING +'  AND  VIEWGJRK.GOODSID = GOODS.GOODSID'
           SELECT  @SQLSTR = @SQLSTR+ ' AND   BILLDATE < '+CHAR(39)+@BEGINDATE +CHAR(39)+'     AND   VIEWGJRK.GOODSID NOT IN (SELECT GOODSID FROM  #temptable1  )   '
           SELECT  @SQLSTR = @SQLSTR+ ' AND   QUANTITY > 0   AND  ( QUANTITY-ISNULL(RETURNQTY,0)) > 0 '
           SELECT  @SQLSTR = @SQLSTR+'  GROUP  BY  VIEWGJRK.GOODSID   '  
           SELECT  @SQLSTR = @SQLSTR+'  order by  VIEWGJRK.GOODSID  '  
            EXEC( @SQLSTR)

Create Table #temptable2
      (ID  varchar(10) primary key,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   VENDORNAME  nvarchar(50)  NULL,
   UNIT  nvarchar(10)  NULL,
	[GRQTY] NUMERIC(20,10)  NULL ,
	[GRAMT] NUMERIC(20,10)  NULL ,
	[CHQTY]NUMERIC(20,10)  NULL ,
	[CHAMT]NUMERIC(20,10)  NULL ,
	[EQTY]NUMERIC(20,10)  NULL ,
	[EAMT]NUMERIC(20,10)  NULL 
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (select   GOODSID, BILLID,PRICE,QUANTITY,TAXRATE   from  #temptable1        )
                 begin
	    declare GJRKMXB_CRGR Cursor for select   GOODSID, BILLID,PRICE,QUANTITY,BILLTYPE,UNITPRICE ,UNITQTY   from  #temptable1  
                                                            ORDER BY  GOODSID,BILLDATE, BILLID
	    Open GJRKMXB_CRGR

	    fetch GJRKMXB_CRGR into   @GOODSID,@BILLID,@PRICE,@QUANTITY,@BILLTYPE,@UNITPRICE ,@UNITQTY  

                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @GOODSCODE='商品编码：'+@GOODSCODE
                 SELECT  @GOODSID00=@GOODSID

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,VENDORNAME         )
                                           VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
		SELECT @SUMAMT=isnull(SUM(QUANTITY*UNITPRICE),0)  FROM  VIEWGJRK  WHERE BILLDATE  < @BEGINDATE  AND GOODSID=@GOODSID
		SELECT @SUMQTY=isnull(SUM(QUANTITY),0)  FROM  VIEWGJRK  WHERE BILLDATE  < @BEGINDATE  AND GOODSID=@GOODSID

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,EAMT,EQTY)
                                           VALUES  (@COUNTID, '期     初',@SUMAMT,@SUMQTY)
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF  not( @GOODSID00 = @GOODSID)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,EAMT,EQTY)
                                           VALUES  (@COUNTID, '期     末',@SUMAMT,@SUMQTY)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @GOODSCODE='商品编码：'+@GOODSCODE
		                 SELECT  @GOODSID00=@GOODSID

			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                          INSERT    INTO   #temptable2  (ID, BILLCODE,VENDORNAME    )
                           	                VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
				SELECT @SUMAMT=isnull(SUM(QUANTITY*UNITPRICE),0)  FROM  VIEWGJRK  WHERE BILLDATE  < @BEGINDATE  AND GOODSID=@GOODSID
				SELECT @SUMQTY=isnull(SUM(QUANTITY),0)  FROM  VIEWGJRK  WHERE BILLDATE  < @BEGINDATE  AND GOODSID=@GOODSID

			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

			                          INSERT    INTO   #temptable2  (ID, BILLCODE,EAMT,EQTY)
                          		                 VALUES  (@COUNTID, '期     初',@SUMAMT,@SUMQTY)

		END	
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	  			SELECT @UNIT = (SELECT UNIT   FROM GOODS  WHERE GOODSID=@GOODSID)

			   SELECT @BILLCODE=(SELECT CODE   FROM STOREGJRKM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STOREGJRKM  WHERE BILLID=@BILLID)
			   SELECT @VENDORID=(SELECT VENDORID   FROM STOREGJRKM  WHERE BILLID=@BILLID)

		                 SELECT  @VENDORNAME=(SELECT NAME   FROM VENDOR  WHERE VENDORID=@VENDORID)

				SELECT @SUMAMT=@SUMAMT+ROUND(@QUANTITY*@UNITPRICE,2)
				SELECT @SUMQTY=@SUMQTY+isnull(@QUANTITY,0)
					IF @QUANTITY>0   
					BEGIN
			                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,VENDORNAME,UNIT, GRQTY,GRAMT,EQTY,EAMT)
             			                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@VENDORNAME,@UNIT,@QUANTITY,
					ROUND(@QUANTITY*@UNITPRICE,2),@SUMQTY,@SUMAMT)
					END
					IF @QUANTITY<0   
					BEGIN
			                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,VENDORNAME,UNIT, CHQTY,CHAMT,EQTY,EAMT)
	             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@VENDORNAME,@UNIT,-@QUANTITY,
					ROUND(-@QUANTITY*@UNITPRICE,2),@SUMQTY,@SUMAMT)
					END
		
	    fetch GJRKMXB_CRGR into   @GOODSID,@BILLID,@PRICE,@QUANTITY,@BILLTYPE,@UNITPRICE ,@UNITQTY  
 
	    END           ------- GJRKMXB_CRGR  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,EAMT,EQTY)
                                           VALUES  (@COUNTID, '期     末',@SUMAMT,@SUMQTY)

	    close GJRKMXB_CRGR
	    deallocate GJRKMXB_CRGR
        end     ------------  if exists

---------------------------------------------------------------------------------------------------相当于处理月结记录
	   if exists (select   GOODSID, QTY,AMT   from  #temptable10        )
                 begin
	    declare GJRKMXB_SEC Cursor for select  GOODSID, QTY,AMT from  #temptable10  
                                                            ORDER BY      GOODSID
	    Open GJRKMXB_SEC

	    fetch GJRKMXB_SEC into   @GOODSID,@SUMQTY,@SUMAMT

	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @GOODSCODE='商品编码：'+@GOODSCODE
                 SELECT  @GOODSID00=@GOODSID

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,VENDORNAME         )
                                           VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,EAMT,EQTY)
                                           VALUES  (@COUNTID, '期     初',@SUMAMT,@SUMQTY)

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,EAMT,EQTY)
                                           VALUES  (@COUNTID, '期     末',@SUMAMT,@SUMQTY)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

	
	    fetch GJRKMXB_SEC into   @GOODSID,@SUMQTY,@SUMAMT
 
	    END           ------- GJRKMXB_SEC  WHILE

	    close GJRKMXB_SEC
	    deallocate GJRKMXB_SEC
        end     ------------  if exists

 SELECT *  FROM #temptable2         ORDER BY ID




----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG









--------------------------------------------------------------------
--------------------------------------------------------------------

CREATE PROCEDURE GOODSGJRKYYYYMMDD(@STOREID varchar(8) ,                        -----如果为0000则全部仓库
                                                                                            @Begin_Date   varchar(10) ,
                                                                                           @End_date   varchar(10) ,  
						           @LCODE  varchar(10),             ---如果LCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSCODE  varchar(20),             ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSNAME  varchar(20),             ---如果GOODSNAME  为‘GGGG’表示不对类别进行查询
                                                                                           @INF_COSTINGTYPEID   smallint      --------同价调拨标志   0  代表 不作为过滤条件

                         
                                                      )     --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @WHERESTING   varchar(1800),
        @STOREIDSTR   varchar(100)

                   set @now_date=(select   max(billDATE)   FROM VIEWGJRK)
		
		IF @now_date IS NULL
		BEGIN
			SET @now_date='2030-12-12'
		END

--@WHERESTR='  and 1=1 '
		if     NOT (@LCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = '  AND   I.GOODSID IN ( select G.GOODSID from GoodsTypetree T, GOODS G where T.indirect_no = '+CHAR(39)+@LCODE+CHAR(39)+ '  AND T.self_no=G.LCODE )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  ='     '
 		END
		if     NOT (@GOODSCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  CODE LIKE   '+CHAR(39)+'%'+@GOODSCODE+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  =@WHERESTING+'     '
 		END
		if     NOT (@GOODSNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  NAME LIKE   '+CHAR(39)+'%'+@GOODSNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END
		if     NOT (@INF_COSTINGTYPEID=0)
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where INF_COSTINGTYPEID =  '+str(@INF_COSTINGTYPEID)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END
		if     NOT (@STOREID='0000')
                           BEGIN
	                           SELECT    @STOREIDSTR   = '    AND   STOREID =  '+CHAR(39)+@STOREID +CHAR(39)
                           END
                           ELSE
                           BEGIN
			SELECT    @STOREIDSTR   = '     '
 		END

----------------------------------------------------
		SELECT @SQLSTR='	 select  I.GOODSID,       '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)   as BQTY, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)   as BAMOUNT, ' --期初金额
		SELECT @SQLSTR=@SQLSTR+'ISNULL(BE.INQTY,0)  AS INQTY   ,-ISNULL(BE00.INQTY,0)  AS OUTQTY,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(BE.INAMOUNT,0)  AS INAMOUNT  ,-ISNULL(BE00.INAMOUNT,0)  AS OUTAMOUNT,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0) '
		SELECT @SQLSTR=@SQLSTR+'+ isnull(BE.INQTY,0)+isnull(BE00.INQTY,0) as EQTY ,' --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)  '
                           SELECT @SQLSTR=@SQLSTR+'+ISNULL(BE.INAMOUNT,0)+ISNULL(BE00.INAMOUNT,0)       as EAMOUNT '--期初金额
		 SELECT @SQLSTR=@SQLSTR+' from Goods  AS  I  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(QUANTITY) as BQTY ,SUM(ROUND(QUANTITY*unitPRICE,2))  AS BAMOUNT'
		 SELECT @SQLSTR=@SQLSTR+' from VIEWGJRK  '
		SELECT @SQLSTR=@SQLSTR+'  where    BILLDATE < '+char(39)+@begin_date+char(39) +@STOREIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(QUANTITY) as INQTY  ,sum(ROUND(QUANTITY*UNITPRICE,2))  as INAMOUNT      '
		 SELECT @SQLSTR=@SQLSTR+' from VIEWGJRK  '
		SELECT @SQLSTR=@SQLSTR+' where  QUANTITY > 0  AND BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+@End_Date+char(39) +@STOREIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE on BE.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(QUANTITY) as INQTY  ,sum(ROUND(QUANTITY*UNITPRICE,2))  as INAMOUNT      '
		 SELECT @SQLSTR=@SQLSTR+' from VIEWGJRK  '
		SELECT @SQLSTR=@SQLSTR+' where   QUANTITY < 0  AND BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+@End_Date+char(39)+@STOREIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE00 on BE00.GOODSID = I.GOODSID  '
                          SELECT @SQLSTR=@SQLSTR+'  where     I. GOODSID in (select GOODSID from  VIEWGJRK   where    BILLDATE <='+char(39)+@End_Date+char(39)+@STOREIDSTR+')'  + @WHERESTING 
		SELECT @SQLSTR=@SQLSTR+'          order by  I.CODE                '   
------------------------------------------------------------------------
		EXEC(@SQLSTR)




----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












--------------------------------------------------------------------

CREATE PROCEDURE GOODSNAME_CF (
                              @GOODSID   varchar(60),   --产品ID
                              @GOODSNAME   varchar(60),   --产品名称 
                              @SPECNAME            varchar(60)     ,      ---产品规格
                              @ISHAVEFLAG         int output     ---没有重复  -- 0 有重复  --1 
                            )  --APSOFTENCRYPTION       WITH ENCRYPTION
 AS 

  if  len(@SPECNAME)=0
  BEGIN
	  if exists (SELECT GOODSID   FROM GOODS  WHERE (GOODSID<>@GOODSID)  AND (SPECNAME  IS NULL)  AND NAME=@GOODSNAME)
	  BEGIN
		SET @ISHAVEFLAG =1
	  END
	  ELSE
	  BEGIN
		SET @ISHAVEFLAG =0
	  END
  END
  ELSE
  BEGIN
	  if exists (SELECT GOODSID   FROM GOODS  WHERE  (GOODSID<>@GOODSID) AND  SPECNAME=@SPECNAME  AND NAME=@GOODSNAME)
	  BEGIN
		SET @ISHAVEFLAG =1
	  END
	  ELSE
	  BEGIN
		SET @ISHAVEFLAG =0
	  END
  END






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG










--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE GOODSXSCKMLRMXB( @WHERESTING   varchar(1800)
                       
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8)

declare @CLIENTNAME  varchar(50)

declare @ID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @BILLTYPE  INT
declare @CLIENTID  nvarchar(50)
declare @GOODSNAME  nvarchar(50)
declare @GOODSCODE  nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLCODE  nvarchar(50)
declare @BILLDATE  datetime
declare @GOODSID00  nvarchar(50)
declare @PRICE NUMERIC(20,10)
declare @QUANTITY NUMERIC(20,10)
declare @TAXRATE  NUMERIC(20,10)
declare @SUMAMT NUMERIC(20,10)
declare @APRICE NUMERIC(20,10)
declare @DISC NUMERIC(20,10)
declare @SUMXSCBAMT NUMERIC(20,10)
declare @AMT NUMERIC(20,10)
declare @ClientFlag smallint 
    

Create Table #temptable1
      (GOODSID  varchar(10) ,
             GOODSCODE  nvarchar(50)  NULL,
             BILLID  nvarchar(50)  NULL,
             BILLTYPE  INT,
	[UNITPRICE] NUMERIC(20,10)  NULL ,
	[APRICE] NUMERIC(20,10)  NULL ,
	[DISC] NUMERIC(20,10)  NULL ,
	[QUANTITY] NUMERIC(20,10)  NULL ,
	[TAXRATE]NUMERIC(20,10)  NULL ,
	BILLDATE DATEtime,
	AMT NUMERIC(20,10)  NULL ,
	[ClientFlag]smallint  NULL 
	)



           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select    VIEWXSCK_2011.GOODSID,GOODS.CODE AS GOODSCODE, BILLID,BILLTYPE,UNITPRICE, VIEWXSCK_2011.APRICE,DISC,QUANTITY,TAXRATE ,BILLDATE, AMT ,ClientFlag '
           SELECT  @SQLSTR = @SQLSTR+'  from VIEWXSCK_2011   ,GOODS  '  + @WHERESTING +'  AND  VIEWXSCK_2011.GOODSID = GOODS.GOODSID'
           SELECT  @SQLSTR = @SQLSTR+'  order by VIEWXSCK_2011.GOODSID,BILLDATE,BILLID '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   CLIENTNAME  nvarchar(50)  NULL,
   UNIT  nvarchar(10)  NULL,
	[QUANTITY] NUMERIC(20,10)  NULL ,
	[PRICE] NUMERIC(20,10)  NULL ,
	[APRICE] NUMERIC(20,10)  NULL ,
	[TAXRATE]NUMERIC(20,10)  NULL ,
	[AMT]NUMERIC(20,10)  NULL ,  ------销售收入
	[XSCBAMT]NUMERIC(20,10)  NULL, ----销售成本
	[MLRAMT]NUMERIC(20,10)  NULL, ----销售成本
	[MLV]NUMERIC(20,10)  NULL ----销售成本
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (select   GOODSID, BILLID,UNITPRICE,APRICE,DISC,QUANTITY,TAXRATE   from  #temptable1        )
                 begin
	    declare XSCKMLRMXB_XSCK Cursor for select   GOODSID, BILLID,UNITPRICE,APRICE,DISC,QUANTITY,TAXRATE,BILLTYPE,AMT,ClientFlag   from  #temptable1  
                                                            ORDER BY  GOODSCODE, BILLDATE,BILLID
	    Open XSCKMLRMXB_XSCK

	    fetch XSCKMLRMXB_XSCK into   @GOODSID,@BILLID,@PRICE,@APRICE,@DISC,@QUANTITY,@TAXRATE,@BILLTYPE,@AMT,@ClientFlag

                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @GOODSCODE='商品编码：'+@GOODSCODE
                 SELECT  @GOODSID00=@GOODSID

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,CLIENTNAME         )
                                           VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
		SELECT @SUMAMT=0
		SELECT @SUMXSCBAMT=0
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF  not( @GOODSID00 = @GOODSID)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,AMT,XSCBAMT)
                                           VALUES  (@COUNTID, '小计',@SUMAMT,@SUMXSCBAMT)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @GOODSCODE='商品编码：'+@GOODSCODE
		                 SELECT  @GOODSID00=@GOODSID

			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                          INSERT    INTO   #temptable2  (ID, BILLCODE,CLIENTNAME    )
                           	                VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
				SELECT @SUMAMT=0
				SELECT @SUMXSCBAMT=0
		END	
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
	  			SELECT @UNIT = (SELECT UNIT   FROM GOODS  WHERE GOODSID=@GOODSID)
			  IF @BILLTYPE=2
			 BEGIN
			   SELECT @BILLCODE=(SELECT CODE   FROM STOREXSCKM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STOREXSCKM  WHERE BILLID=@BILLID)
			   SELECT @CLIENTID=(SELECT CLIENTID   FROM STOREXSCKM  WHERE BILLID=@BILLID)
			END
			  IF @BILLTYPE=12
			 BEGIN
			   SELECT @BILLCODE=(SELECT CODE   FROM STOREXSTHM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STOREXSTHM  WHERE BILLID=@BILLID)
			   SELECT @CLIENTID=(SELECT CLIENTID   FROM STOREXSTHM  WHERE BILLID=@BILLID)
			END
	                 SELECT  @CLIENTNAME =(SELECT NAME   FROM ViewCLIENT  WHERE CLIENTID=@CLIENTID  and CLIENTFlag=@CLIENTFlag)

				set   @PRICE=@AMT/@QUANTITY

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,CLIENTNAME,UNIT, QUANTITY,PRICE,APRICE,TAXRATE, AMT,XSCBAMT)
             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@CLIENTNAME,@UNIT,@QUANTITY,@PRICE,@APRICE,@TAXRATE,
					ROUND(@QUANTITY*@PRICE*@DISC*0.01,2),ROUND(@QUANTITY*@APRICE,2))
				SELECT @SUMAMT=@SUMAMT+ROUND(@QUANTITY*@PRICE*@DISC*0.01,2)
				SELECT @SUMXSCBAMT=@SUMXSCBAMT+ROUND(@QUANTITY*@APRICE,2)
		
	    fetch XSCKMLRMXB_XSCK into   @GOODSID,@BILLID,@PRICE,@APRICE,@DISC,@QUANTITY,@TAXRATE,@BILLTYPE,@AMT,@ClientFlag
 
	    END           ------- XSCKMLRMXB_XSCK  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,AMT,XSCBAMT)
                                           VALUES  (@COUNTID, '小计',@SUMAMT,@SUMXSCBAMT)

	    close XSCKMLRMXB_XSCK
	    deallocate XSCKMLRMXB_XSCK
        end     ------------  if exists

	UPDATE   #temptable2   SET MLRAMT=AMT- XSCBAMT
	UPDATE   #temptable2   SET MLV=(MLRAMT/ AMT)*100   WHERE AMT<>0

 SELECT *  FROM #temptable2         ORDER BY ID







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE GOODSXSCKMXB( @WHERESTING   varchar(1800)
                       
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8)

declare @CLIENTNAME  varchar(50)

declare @ID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @BILLTYPE  INT
declare @PRICETYPE  INT
declare @CLIENTID  nvarchar(50)
declare @GOODSNAME  nvarchar(50)
declare @GOODSCODE  nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLCODE  nvarchar(50)
declare @BILLDATE  datetime
declare @GOODSID00  nvarchar(50)
declare @PRICE NUMERIC(20,10)
declare @QUANTITY NUMERIC(20,10)
declare @TAXRATE  NUMERIC(20,10)
declare @FuZhuQTY  varchar(50)
declare @SUMAMT NUMERIC(20,10)
declare @DISC NUMERIC(20,10)
declare @SUMTAXAMT NUMERIC(20,10)
declare @AMT NUMERIC(20,10)
declare @TAXAMT NUMERIC(20,10)
declare @UNITPRICE  NUMERIC(20,10)
declare @UNITQTY  NUMERIC(20,10)
declare @ClientFlag smallint 
declare @DunQTY NUMERIC(20,10)
declare @Rate NUMERIC(20,10)
declare @SumDunQTY NUMERIC(20,10)
    

Create Table #temptable1
      (GOODSID  varchar(10) ,
             GOODSCODE nvarchar(50)  NULL,
             BILLID  nvarchar(50)  NULL,
             BILLTYPE INT,
	[PRICE] NUMERIC(20,10)  NULL ,
	[DISC] NUMERIC(20,10)  NULL ,
	[QUANTITY] NUMERIC(20,10)  NULL ,
	[TAXRATE]NUMERIC(20,10)  NULL ,
	FuZhuQTY  varchar(50)  NULL,
	BILLDATE DATEtime,
	[UNITPRICE] NUMERIC(20,10)  NULL ,
	[UNITQTY]NUMERIC(20,10)  NULL ,
		     PRICETYPE  INT ,
	[AMT]NUMERIC(20,10)  NULL ,
	[TAXAMT]NUMERIC(20,10)  NULL, 
	[ClientFlag]smallint  NULL 
	)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select    VIEWXSCK.GOODSID,GOODS.CODE AS GOODSCODE, BILLID,BILLTYPE,VIEWXSCK.PRICE,DISC,QUANTITY,TAXRATE,FuZhuQTY,BILLDATE  '
           SELECT  @SQLSTR = @SQLSTR+' ,UNITPRICE,UNITQTY,PRICETYPE,AMT,TAXAMT,ClientFlag from VIEWXSCK   ,GOODS  '  + @WHERESTING +'  AND  VIEWXSCK.GOODSID = GOODS.GOODSID'
           SELECT  @SQLSTR = @SQLSTR+'  order by VIEWXSCK.GOODSID,BILLDATE,BILLID '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   CLIENTNAME  nvarchar(50)  NULL,
   UNIT  nvarchar(10)  NULL,
	[QUANTITY] NUMERIC(20,10)  NULL ,
	[PRICE] NUMERIC(20,10)  NULL ,
	[TAXRATE]NUMERIC(20,10)  NULL ,
	FuZhuQTY  varchar(50)  NULL,
	[AMT]NUMERIC(20,10)  NULL ,
	[TAXAMT]NUMERIC(20,10)  NULL ,
   		PRICETYPENAME  nvarchar(10)  NULL,
	[DunQTY]NUMERIC(20,10)  NULL 
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (select   GOODSID, BILLID,PRICE,DISC,QUANTITY,TAXRATE   from  #temptable1        )
                 begin
	    declare XSCKMXB_XSCK Cursor for select   GOODSID, BILLID,PRICE,DISC,QUANTITY,TAXRATE,FuZhuQTY,BILLTYPE,UNITPRICE,UNITQTY,PRICETYPE,AMT,TAXAMT,ClientFlag  from  #temptable1  
                                                            ORDER BY  GOODSCODE,BILLDATE, BILLID
	    Open XSCKMXB_XSCK

	    fetch XSCKMXB_XSCK into   @GOODSID,@BILLID,@PRICE,@DISC,@QUANTITY,@TAXRATE,@FuZhuQTY,@BILLTYPE,@UNITPRICE,@UNITQTY,@PRICETYPE,@AMT,@TAXAMT,@ClientFlag

                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @GOODSCODE='商品编码：'+@GOODSCODE
                 SELECT  @GOODSID00=@GOODSID

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,CLIENTNAME         )
                                           VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
		SELECT @SUMAMT=0
		SELECT @SUMTAXAMT=0
		SELECT @SUMDunQTY=0
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF  not( @GOODSID00 = @GOODSID)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,AMT,TAXAMT,DunQTY)
                                           VALUES  (@COUNTID, '小计',@SUMAMT,@SUMTAXAMT,@SumDunQTY)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @GOODSCODE='商品编码：'+@GOODSCODE
		                 SELECT  @GOODSID00=@GOODSID

			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                          INSERT    INTO   #temptable2  (ID, BILLCODE,CLIENTNAME    )
                           	                VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
				SELECT @SUMAMT=0
				SELECT @SUMTAXAMT=0
				SELECT @SUMDunQTY=0
		END	
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
	  			SELECT @UNIT = (SELECT UNIT   FROM GOODS  WHERE GOODSID=@GOODSID)
			  IF @BILLTYPE=2
			 BEGIN
			   SELECT @BILLCODE=(SELECT CODE   FROM STOREXSCKM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STOREXSCKM  WHERE BILLID=@BILLID)
			   SELECT @CLIENTID=(SELECT CLIENTID   FROM STOREXSCKM  WHERE BILLID=@BILLID)
			END
			  IF @BILLTYPE=12
			 BEGIN
			   SELECT @BILLCODE=(SELECT CODE   FROM STOREXSTHM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STOREXSTHM  WHERE BILLID=@BILLID)
			   SELECT @CLIENTID=(SELECT CLIENTID   FROM STOREXSTHM  WHERE BILLID=@BILLID)
			END
	                 SELECT  @CLIENTNAME =(SELECT NAME   FROM ViewCLIENT  WHERE CLIENTID=@CLIENTID  and CLIENTFlag=@CLIENTFlag)

				IF @PRICETYPE=1 
				BEGIN
			                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,CLIENTNAME,UNIT, QUANTITY,PRICE,TAXRATE,FuZhuQTY, AMT,TAXAMT,PRICETYPENAME,DunQTY)
	             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@CLIENTNAME,@UNIT,@UNITQTY,@unitPRICE,@TAXRATE,@FuZhuQTY,@AMT,@TAXAMT,'重量',@QUANTITY)
					set @DunQTY=@QUANTITY
				END
				IF @PRICETYPE=0
				BEGIN
		                 SELECT  @Rate =(SELECT ISNULL(Rate,0) FROM GOODS  WHERE GOODSID=@GOODSID)
			                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,CLIENTNAME,UNIT, QUANTITY,PRICE,TAXRATE,FuZhuQTY, AMT,TAXAMT,PRICETYPENAME,DunQTY)
	             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@CLIENTNAME,@UNIT,@UNITQTY,@UNITPRICE,@TAXRATE,@FuZhuQTY,@AMT,@TAXAMT,'数量',@Rate*@UNITQTY)
					set @DunQTY=@Rate*@UNITQTY
				END
				SELECT @SUMAMT=@SUMAMT+@AMT
				SELECT @SUMTAXAMT=@SUMTAXAMT+@TAXAMT
				SELECT @SUMDunQTY=@SUMDunQTY+@DunQTY
		
	    fetch XSCKMXB_XSCK into   @GOODSID,@BILLID,@PRICE,@DISC,@QUANTITY,@TAXRATE,@FuZhuQTY,@BILLTYPE,@UNITPRICE,@UNITQTY,@PRICETYPE,@AMT,@TAXAMT,@ClientFlag
 
	    END           ------- XSCKMXB_XSCK  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,AMT,TAXAMT,DunQTY)
                                           VALUES  (@COUNTID, '小计',@SUMAMT,@SUMTAXAMT,@SumDunQTY)

	    close XSCKMXB_XSCK
	    deallocate XSCKMXB_XSCK
        end     ------------  if exists

 SELECT *  FROM #temptable2         ORDER BY ID








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG







--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE [dbo].[GOODSXSDDMXB]( @WHERESTING   varchar(1800)
                       
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8)

declare @CLIENTNAME  varchar(50)
declare @GOODSNAME  varchar(50)

declare @ID  nvarchar(50)
declare @CLIENTID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @CLIENTCODE  nvarchar(50)
declare @GOODSCODE  nvarchar(50)
declare @SPECNAME nvarchar(50)
declare @MODELNAME nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLCODE  nvarchar(50)
declare @BILLTYPE INT
declare @BILLDATE  datetime
declare @GOODSID00  nvarchar(50)
declare @PRICE NUMERIC(20, 6)
declare @TAXAMT NUMERIC(20, 2)
declare @WCunitQTY NUMERIC(20, 6)
declare @WCquantity NUMERIC(20, 6)
declare @zzunitQTY NUMERIC(20, 6)
declare @zzquantity NUMERIC(20, 6)
declare @WCTAXAMT NUMERIC(20, 6)
declare @TAXRATE  NUMERIC(20, 6)
declare @RATE  NUMERIC(20, 6)
declare @WEITAXAMT NUMERIC(20, 6)
declare @SUMWCTAXAMT NUMERIC(20, 6)
declare @SUMWEITAXAMT NUMERIC(20, 6)
declare @SUMTAXAMT NUMERIC(20, 6)
declare @UNITQTY NUMERIC(20, 6)
declare @quantity NUMERIC(20, 6)
declare @UNITPRICE NUMERIC(20, 6)
declare @DISC NUMERIC(20, 6)
declare    @PRICETYPE int

Create Table #temptable1
      (   GOODSID varchar(50)  NULL,
       CLIENTID  varchar(10) ,
       CLIENTCODE  varchar(30) ,
      BILLID  nvarchar(50)  NULL,
      BILLTYPE  INT ,
	[PRICE] NUMERIC(20, 6)  NULL ,
	[UNITQTY] NUMERIC(20, 6)  NULL ,
	[quantity] NUMERIC(20, 6)  NULL ,
	[DISC] NUMERIC(20, 6)  NULL ,
	[TAXRATE]NUMERIC(20, 6)  NULL ,
	   BILLDATE  datetime  NULL,
	[UNITPRICE] NUMERIC(20, 6)  NULL ,
	[WCunitQTY]NUMERIC(20, 6)  NULL ,
	[WCquantity]NUMERIC(20, 6)  NULL ,
	[zzunitQTY]NUMERIC(20, 6)  NULL ,
	[zzquantity]NUMERIC(20, 6)  NULL ,
	[TAXAMT]NUMERIC(20, 2)  NULL, 
	[PRICETYPE]    int  NULL, 
	       DETAILBILLFLOWID  varchar(10) 
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   VIEWXSDD.GOODSID,VIEWXSDD.CLIENTID,CLIENT.CODE AS CLIENTCODE, BILLID,BILLTYPE,PRICE,UNITQTY,quantity,DISC,TAXRATE,BILLDATE '
           SELECT  @SQLSTR = @SQLSTR+' ,UNITPRICE,WCunitQTY,WCquantity,zzunitQTY,zzquantity,TAXAMT,PRICETYPE,DETAILBILLFLOWID  from VIEWXSDD   ,CLIENT  '  + @WHERESTING +'  AND  VIEWXSDD.CLIENTID = CLIENT.CLIENTID'
           SELECT  @SQLSTR = @SQLSTR+'  order by VIEWXSDD.GOODSID,VIEWXSDD.CLIENTID,BILLDATE,DETAILBILLFLOWID '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
	   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   CLIENTNAME  nvarchar(50)  NULL,
   CLIENTCODE  nvarchar(50)  NULL,
   UNIT  nvarchar(10)  NULL,
	[UNITQTY] NUMERIC(20, 6)  NULL ,
	[quantity] NUMERIC(20, 6)  NULL ,
	[TAXAMT]NUMERIC(20, 2)  NULL, 
	[WCunitQTY] NUMERIC(20, 6)  NULL ,
	[WCquantity] NUMERIC(20, 6)  NULL ,
	[zzunitQTY] NUMERIC(20, 6)  NULL ,
	[zzquantity] NUMERIC(20, 6)  NULL ,
	[WCTAXAMT]NUMERIC(20, 6)  NULL ,
	[WEIunitQTY] NUMERIC(20, 6)  NULL ,
	[WEIquantity] NUMERIC(20, 6)  NULL ,
	[WEITAXAMT]NUMERIC(20, 6)  NULL 
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (select  GOODSID, CLIENTID, BILLID,PRICE,UNITQTY,TAXRATE,BILLTYPE   from  #temptable1        )
                 begin
	    declare XSDDMXB_GOODS Cursor for select  GOODSID, CLIENTID, BILLID,PRICE,UNITQTY,quantity,TAXRATE,BILLTYPE ,DISC,UNITPRICE,WCunitQTY,WCquantity, zzunitQTY,zzquantity,TAXAMT,PRICETYPE  from  #temptable1  
---                                                            ORDER BY  GOODSID,  BILLDATE,DETAILBILLFLOWID,CLIENTCODE
                                                            ORDER BY  GOODSID,  BILLDATE,BILLID,CLIENTCODE
	    Open XSDDMXB_GOODS

	    fetch XSDDMXB_GOODS into   @GOODSID,@CLIENTID,@BILLID,@PRICE,@UNITQTY,@quantity,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@WCunitQTY,@WCquantity,@zzunitQTY,@zzquantity,@TAXAMT,@PRICETYPE

                 SELECT  @CLIENTNAME =(SELECT NAME   FROM CLIENT  WHERE CLIENTID=@CLIENTID)
                 SELECT  @CLIENTCODE =(SELECT CODE  FROM CLIENT  WHERE CLIENTID=@CLIENTID)
                 SELECT  @GOODSCODE=CODE,@GOODSNAME=Name,@SpecName=SpecName,@ModelName=ModelName     FROM GOODS  WHERE GOODSID=@GOODSID
                 SELECT  @GOODSNAME =@GOODSNAME+' '+ISNULL(@SpecName,'')+' '+ISNULL(@ModelName,'')
                 SELECT  @GOODSCODE='钢材编码：'+@GOODSCODE

                 SELECT  @GOODSID00=@GOODSID

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,CLIENTNAME         )
                                           VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
		SELECT @SUMWCTAXAMT=0
		SELECT @SUMTAXAMT=0
		SELECT @SUMWEITAXAMT=0
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF  not( @GOODSID00 = @GOODSID)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,WCTAXAMT,TAXAMT,WEITAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMWCTAXAMT,@SUMTAXAMT,@SUMWEITAXAMT)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

		                 SELECT  @CLIENTNAME =(SELECT NAME   FROM CLIENT  WHERE CLIENTID=@CLIENTID)
		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @CLIENTCODE =(SELECT CODE  FROM CLIENT  WHERE CLIENTID=@CLIENTID)
                 SELECT  @GOODSCODE=CODE,@GOODSNAME=Name,@SpecName=SpecName,@ModelName=ModelName     FROM GOODS  WHERE GOODSID=@GOODSID
                 SELECT  @GOODSNAME =@GOODSNAME+' '+ISNULL(@SpecName,'')+' '+ISNULL(@ModelName,'')
                 SELECT  @GOODSCODE='钢材编码：'+@GOODSCODE
		                 
		                 SELECT  @GOODSID00=@GOODSID


			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,CLIENTNAME         )
                                           VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
				SELECT @SUMWCTAXAMT=0
				SELECT @SUMTAXAMT=0
				SELECT @SUMWEITAXAMT=0
		END	
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

				--SELECT @RATE =RATE  FROM CLIENTUNIT  WHERE CLIENTID=@CLIENTID AND UNITID=@UNITID

			SELECT @UNIT = UNIT   FROM GOODS  WHERE GOODSID=@GOODSID
				
			   SELECT @BILLCODE=(SELECT CODE   FROM STOREXSDDM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STOREXSDDM  WHERE BILLID=@BILLID)
		                 SELECT  @CLIENTNAME=(SELECT NAME   FROM CLIENT  WHERE CLIENTID=@CLIENTID)
		                 SELECT  @CLIENTCODE=(SELECT CODE   FROM CLIENT  WHERE CLIENTID=@CLIENTID)
		               if @PRICETYPE=1
		               begin  
		                 SET @WEITAXAMT=Round(ISNULL(@DISC,100)*0.01*(ISNULL(@quantity,0)-ISNULL(@WCquantity,0)-ISNULL(@zzquantity,0))*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
		                 SET @WCTAXAMT=Round(ISNULL(@DISC,100)*0.01*ISNULL(@WCquantity,0)*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
					   end
					   else
					   begin
		                 SET @WEITAXAMT=Round(ISNULL(@DISC,100)*0.01*(ISNULL(@unitqty,0)-ISNULL(@WCunitqty,0)-ISNULL(@zzunitqty,0))*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
		                 SET @WCTAXAMT=Round(ISNULL(@DISC,100)*0.01*ISNULL(@WCunitqty,0)*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
					   end
		                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,CLIENTNAME,CLIENTCODE,UNIT, UNITQTY,quantity,TAXAMT,WCunitQTY,WCquantity,zzunitQTY,zzquantity,WCTAXAMT,WEIunitQTY,WEIquantity,WEITAXAMT)
             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@CLIENTNAME,@CLIENTCODE,@UNIT,@UNITQTY,@quantity,
					                     @TAXAMT,
					                     ISNULL(@WCunitQTY,0) ,
					                     ISNULL(@WCquantity,0) ,
					                     ISNULL(@zzunitQTY,0) ,
					                     ISNULL(@zzquantity,0) ,					@WCTAXAMT,
					                      @UNITQTY-ISNULL(@WCunitQTY,0) -ISNULL(@zzunitQTY,0),
					                      @quantity-ISNULL(@WCquantity,0) -ISNULL(@zzquantity,0),@WEITAXAMT	)

				SELECT @SUMTAXAMT=@SUMTAXAMT+@TAXAMT
				SELECT @SUMWCTAXAMT=@SUMWCTAXAMT+@WCTAXAMT
				SELECT @SUMWEITAXAMT=@SUMWEITAXAMT+@WEITAXAMT
		
	    fetch XSDDMXB_GOODS into   @GOODSID,@CLIENTID,@BILLID,@PRICE,@UNITQTY,@quantity,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@WCunitQTY,@WCquantity,@zzunitQTY,@zzquantity,@TAXAMT,@PRICETYPE
 
	    END           ------- XSDDMXB_GOODS  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,WCTAXAMT,TAXAMT,WEITAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMWCTAXAMT,@SUMTAXAMT,@SUMWEITAXAMT)

	    close XSDDMXB_GOODS
	    deallocate XSDDMXB_GOODS
        end     ------------  if exists

 SELECT *  FROM #temptable2         ORDER BY ID












----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG



















--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE GOODS_STOREMXB( @WHERESTING   varchar(1800),
                                  @ShowFLAG   smallint,      --------同价调拨标志   0  代表 不作为过滤条件
                                  @LiuHuoShowFLAG   smallint      --------同价调拨标志   0  代表 不作为过滤条件

                      
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @SQLSTR00   varchar(800),
        @SQLSTR2005   varchar(800),
        @COUNTID   varchar(8)

declare @CLIENTNAME  varchar(50)

declare @ID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @STOREID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @CLIENTID  nvarchar(50)
declare @GOODSNAME  nvarchar(50)
declare @GOODSCODE  nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLCODE  nvarchar(50)
declare @YYYYMM  nvarchar(50)
declare @STORENAME  nvarchar(50)
declare @BILLDATE  datetime
declare @GOODSID00  nvarchar(50)
declare @PRICE NUMERIC(16,4)
declare @QUANTITY NUMERIC(16,4)
declare @STOREIDEQTY NUMERIC(16,4)
declare @TAXRATE  NUMERIC(16,4)
declare @SUMQTY NUMERIC(16,4)
declare @APRICE NUMERIC(16,4)
declare @DISC NUMERIC(16,4)
declare @SUMXSCBAMT NUMERIC(16,4)
declare @NameLen int
declare @SpecNameLen int


 		SELECT @YYYYMM=( SELECT   optionvalue     FROM  accoptionS     where optionname ='YYYYMM')






/*Create Table DB_STORELEDGER
      (GOODSID  varchar(10) ,
       StoreID  varchar(10) ,
	  EQTY NUMERIC(16,4)  NULL, 
	  MEQTY NUMERIC(16,4)  NULL 
		)
*/
----------------------------------------------------
/*Create Table DB_STORELEDGER_Root
      (StoreID  varchar(10) ,
       GOODSID  varchar(10) 
		)
*/
----------------------------------------------------
			delete DB_STORELEDGER_Root

			INSERT INTO  DB_STORELEDGER_Root select distinct StoreID,GOODSID from DETAILBILLFLOW

			delete DB_STORELEDGER

		SELECT @SQLSTR='	 select  I.GOODSID,I.StoreID,       '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)+ isnull(E.INQTY,0)  as EQTY, '   --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0)  as MEQTY '   --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from DB_STORELEDGER_Root  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,StoreID,sum(INQTY*INOUTFLAG)  as INQTY  ,sum(MINQTY*INOUTFLAG)  as MINQTY '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID,StoreID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID AND  E.StoreID = I.StoreID '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,StoreID,sum(BQTY) as BQTY ,sum(MBQTY) as MBQTY '
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID,StoreID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID AND B.StoreID = I.StoreID '
------------------------以上部分是取当前库存
----		print @SQLSTR

		INSERT INTO  DB_STORELEDGER  EXEC(@SQLSTR)


-----------------------------------------------------------------------------------------


	if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODSSTORETMP]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table [dbo].[GOODSSTORETMP]


----
		select @NameLen=max(Len(Name)) from Goods
		select @NameLen=2*(@NameLen+1) 
		select @SpecNameLen=max(Len(SpecName)) from Goods
		select @SpecNameLen=1.5*(@SpecNameLen+1) 


	    if @LiuHuoShowFLAG =1 
	    begin
	    declare STORE_XSCK Cursor for select   STOREID   from  STORE    ORDER BY CODE
 	    end
	    else
	    begin
	    declare STORE_XSCK Cursor for select   STOREID   from  STORE  where liuhflag<>1   ORDER BY CODE
 	    end

	  
	    Open   STORE_XSCK

	    fetch    STORE_XSCK into   @STOREID
	           SELECT  @SQLSTR = 'Create Table GOODSSTORETMP (  '
	           SELECT  @SQLSTR = @SQLSTR+' 商品编码 [varchar] (20), '
---	           SELECT  @SQLSTR = @SQLSTR+' 商品名称 [varchar] (80), '
	           SELECT  @SQLSTR = @SQLSTR+' 商品名称 [varchar] ('+convert(char,@NameLen)+'), '
---	           SELECT  @SQLSTR = @SQLSTR+' 规格   [varchar] (50), '
	           SELECT  @SQLSTR = @SQLSTR+' 规格   [varchar] ('+convert(char,@SpecNameLen)+'), '
	           SELECT  @SQLSTR = @SQLSTR+' 单位   [varchar] (8), '

	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    BEGIN

	           SELECT  @SQLSTR =@SQLSTR+'['+@STOREID+']'+' NUMERIC(16,4)  NULL ,'

		    fetch    STORE_XSCK into   @STOREID

	    END
	    close  STORE_XSCK
	    deallocate  STORE_XSCK

	           SELECT  @SQLSTR =@SQLSTR+'   合计   NUMERIC(16,4)  NULL )  '

                EXEC( @SQLSTR)

		set  @SQLSTR2005 =' 	insert  into   GOODSSTORETMP (商品编码,商品名称,规格,单位)    '
		set  @SQLSTR2005 =@SQLSTR2005+'	  SELECT  CODE,NAME,SPECNAME,UNIT  FROM GOODS  '
		set  @SQLSTR2005 =@SQLSTR2005+'	  WHERE GOODSID IN (SELECT GOODSID FROM DETAILBILLFLOW)  '+@WHERESTING
		exec(@SQLSTR2005)

--				insert  into   GOODSSTORETMP (商品编码,商品名称,规格,单位)    
--				  SELECT  CODE,NAME,SPECNAME,UNIT  FROM GOODS  
--				  WHERE GOODSID IN (SELECT GOODSID FROM DETAILBILLFLOW) 

-------------------------------以上是创建数据库


	    declare STORE_TMP Cursor for select   商品编码   from  GOODSSTORETMP

                                                                 ORDER BY 商品编码
	    Open   STORE_TMP

	    fetch    STORE_TMP into   @GOODSCODE


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    BEGIN
		SET @SUMQTY=0

		SELECT @GOODSID=(SELECT GOODSID FROM GOODS WHERE CODE= @GOODSCODE)
	    if @LiuHuoShowFLAG =1 
	    begin

		    declare STORE_XSCK00 Cursor for select   STOREID   from  STORE  ORDER BY CODE
 	    end
	    else
	    begin
		    declare STORE_XSCK00 Cursor for select   STOREID   from  STORE  where liuhflag<>1   ORDER BY CODE
 	    end


		    Open   STORE_XSCK00

		    fetch    STORE_XSCK00 into   @STOREID

		    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
		    BEGIN

				SET @STOREIDEQTY=0
				IF @ShowFLAG =1
				begin
---        	                    	 EXEC   GETGOODSIDMEQTY  @STOREID,@GOODSID,@YYYYMM,@MEQTY=@STOREIDEQTY   OUTPUT
					select @STOREIDEQTY=MEQTY from DB_STORELEDGER where GoodsID=@GOODSID and STOREID=@STOREID
				end
				IF @ShowFLAG =2
				begin
---	                              EXEC   GETGOODSIDEQTY     @STOREID,@GOODSID,@YYYYMM,@EQTY=@STOREIDEQTY   OUTPUT
					select @STOREIDEQTY=EQTY from DB_STORELEDGER where GoodsID=@GOODSID and STOREID=@STOREID
				end
				
				SET @SUMQTY=@SUMQTY+ISNULL(@STOREIDEQTY,0)
	
				SET @SQLSTR00 ='     UPDATE   GOODSSTORETMP  set  '+'['+@STOREID+']'+' ='+ CAST(@STOREIDEQTY  AS varchar(30))  +'   WHERE  商品编码='+CHAR(39)+@GOODSCODE+CHAR(39) 
				                EXEC( @SQLSTR00)

			    fetch    STORE_XSCK00  into   @STOREID

		    END
		    close  STORE_XSCK00
		    deallocate  STORE_XSCK00

			UPDATE GOODSSTORETMP  SET  合计=@SUMQTY   WHERE  商品编码=@GOODSCODE
		    fetch    STORE_TMP into   @GOODSCODE

	    END
	    close  STORE_TMP
	    deallocate  STORE_TMP

-------------------------
	    if @LiuHuoShowFLAG =1 
	    begin
	    declare STORE_XSCK Cursor for select   STOREID,STORENAME   from  STORE  ORDER BY CODE
 	    end
	    else
	    begin
	    declare STORE_XSCK Cursor for select   STOREID,STORENAME   from  STORE  where liuhflag<>1   ORDER BY CODE
 	    end

	    Open   STORE_XSCK

	    fetch    STORE_XSCK into   @STOREID,@STORENAME

	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    BEGIN


	           SELECT  @SQLSTR ='ALTER TABLE  GOODSSTORETMP  ADD  '+'['+@STORENAME+']'+' NUMERIC(16,4)  NULL '
		                EXEC( @SQLSTR)
	           SELECT  @SQLSTR ='UPDATE  GOODSSTORETMP   SET   '+'['+@STORENAME+']'+' = ['+@STOREID+']'
		                EXEC( @SQLSTR)
	           SELECT  @SQLSTR ='ALTER TABLE  GOODSSTORETMP  DROP   COLUMN '+'['+@STOREID+']'
		                EXEC( @SQLSTR)
		    fetch    STORE_XSCK into   @STOREID,@STORENAME

	    END
	    close  STORE_XSCK
	    deallocate  STORE_XSCK


  SELECT   *    FROM  GOODSSTORETMP  where 合计 <>0  ORDER BY 商品编码  










----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











-------本会计期间返回值为 Billdate >=@MINBILLDATE  AND  Billdate<@MAXBILLDATE

--------------------------------------------------------------------

CREATE PROCEDURE Get_Max_Min_Date  
                 (
                  @MAXBILLDATE DATEtime output,     ---返回记帐成功  -- 0 不在此会计期间  --1 在会计期间
                  @MINBILLDATE DATEtime output     ---返回记帐成功  -- 0 不在此会计期间  --1 在会计期间
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     

---declare @MINBILLDATE DATEtime
---declare @MAXBILLDATE DATEtime


   declare  @PREV_YYYYMM          varchar(6)  -- 上一个会计年月
   declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='CW_YYYYMM')  

   
	if substring(@YYYYMM,5,2) = '12'  --- 如果当前会计月等于最大的会计月，将需要转入下年的的第一个会计年月
	begin
	    set @Next_YYYYMM   = convert(varchar,convert(int,substring(@YYYYMM,1,4))+1) +'01'  
	end
	else
	begin
	    set @Next_YYYYMM   = substring(@YYYYMM,1,4) +substring('00',1,2-len(convert(varchar,convert(int,substring(@YYYYMM,5,2))+1)))+convert(varchar,convert(int,substring(@YYYYMM,5,2))+1)
	end

	if substring(@YYYYMM,5,2) = '01'  --- 如果当前会计月等于最大的会计月，将需要转入下年的的第一个会计年月
	begin
	    set @PREV_YYYYMM   = convert(varchar,convert(int,substring(@YYYYMM,1,4))-1) +'12'  
	end
	else
	begin
	    set @PREV_YYYYMM   = substring(@YYYYMM,1,4) +substring('00',1,2-len(convert(varchar,convert(int,substring(@YYYYMM,5,2))-1)))+convert(varchar,convert(int,substring(@YYYYMM,5,2))-1)
	end

	declare @YYYYMMFS INTEGER
	declare @YYYYMMFSDATE  INTEGER
	declare @Billday  INTEGER

	       SELECT    @YYYYMMFS =(SELECT  YYYYMMFS   FROM   ACCINFO    WHERE   GUID='0001' )    
                IF @YYYYMMFS=1
	  BEGIN
		     SET  @MINBillDate = CONVERT(DATEtime,@YYYYMM+'01')
		     SET  @MAXBillDate =CONVERT(DATEtime,@Next_YYYYMM+'01')
	  END
               ELSE
               BEGIN
	       SELECT    @YYYYMMFSDATE =(SELECT  YYYYMMFSDATE   FROM   ACCINFO    WHERE   GUID='0001' )    
       
	     SET  @MINBillDate =DATEADD(day, @YYYYMMFSDATE, CONVERT(DATEtime,@PREV_YYYYMM+'01'))
	     SET  @MAXBillDate =DATEADD(day, @YYYYMMFSDATE, CONVERT(DATEtime,@YYYYMM+'01'))
	 END


----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











--------------------------------------------------------------------
--------------------------------------------------------------------

CREATE PROCEDURE INSERTTOSecurity (
                              @USERID   varchar(20),   --传入当前操作员
                              @IsSuccess         int output     ---返回成功  -- 0 不成功  --1 
                            )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
Begin transaction SMDataToNext

                      UPDATE FunctionM  SET USERID=@USERID
                      INSERT INTO Security  (USERID,Function_id ,Parent_Function_Id,Control_Type )
                                 SELECT    USERID, Function_id ,Parent_Function_Id,Control_Type      FROM  FunctionM  where Function_id  not in (select Function_id   from  Security  where  USERID=@USERID)  
                      update  Security   set    CANACCESS=1      where  userid='0001'
                      DELETE   FROM    Security    WHERE   Function_id NOT  IN ( SELECT  Function_id   FROM     FunctionM         )


--写结转信息
  If @@error = 0
  begin
     commit transaction SMDataToNext
   set @IsSuccess=1
  end
  else
  begin
    rollback transaction SMDataToNext
   set @IsSuccess=0
    raiserror('结转失败 ', 1, 20) 
  end
  






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













----------------------------------------------------------------------------
CREATE PROCEDURE [QTSRBILLTREE]  (  @INSQLSTRING  varchar(300)    )  --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 

Declare @SQL				varchar(8000)

 
BEGIN

	SELECT @SQL= 'select SUBSTRING(GOODSNOJS,1,4) as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWQTSRJSNO'
	SELECT @SQL=@SQL+'  WHERE   SUBSTRING(GOODSNOJS,1,4) in (select lcode FROM INTYPE)    ' +@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY SUBSTRING(GOODSNOJS,1,4)'
	SELECT @SQL=@SQL+' union '
	SELECT @SQL=@SQL+' select SUBSTRING(GOODSNOJS,5,4) as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWQTSRJSNO'
	SELECT @SQL=@SQL+'  where   SUBSTRING(GOODSNOJS,5,4) in (select lcode FROM INTYPE) '+@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY SUBSTRING(GOODSNOJS,5,4)'
	SELECT @SQL=@SQL+' union '
	SELECT @SQL=@SQL+' select SUBSTRING(GOODSNOJS,9,4) as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWQTSRJSNO'
	SELECT @SQL=@SQL+'  where   SUBSTRING(GOODSNOJS,9,4) in (select lcode FROM INTYPE) '+@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY SUBSTRING(GOODSNOJS,9,4)'
	SELECT @SQL=@SQL+' union '
	SELECT @SQL=@SQL+' select SUBSTRING(GOODSNOJS,13,4) as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWQTSRJSNO'
	SELECT @SQL=@SQL+'  where   SUBSTRING(GOODSNOJS,13,4) in (select lcode FROM INTYPE) '+@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY SUBSTRING(GOODSNOJS,13,4)'
	SELECT @SQL=@SQL+' union '
	SELECT @SQL=@SQL+' select SUBSTRING(GOODSNOJS,17,4) as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWQTSRJSNO'
	SELECT @SQL=@SQL+'  where   SUBSTRING(GOODSNOJS,17,4) in (select lcode FROM INTYPE) '+@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY SUBSTRING(GOODSNOJS,17,4)'
	SELECT @SQL=@SQL+' union '
	SELECT @SQL=@SQL+' select SUBSTRING(GOODSNOJS,21,4) as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWQTSRJSNO'
	SELECT @SQL=@SQL+'  where   SUBSTRING(GOODSNOJS,21,4) in (select lcode FROM INTYPE) '+@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY SUBSTRING(GOODSNOJS,21,4)'
	SELECT @SQL=@SQL+' union '
	SELECT @SQL=@SQL+' select  STOREID as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWQTSRJSNO'
	SELECT @SQL=@SQL+'  where   1 = 1 '+@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY STOREID '
		EXEC(@SQL)
----注意INTYPE  中的LCODE不能和GOODS中的STOREID 重码，以后补充检测过程
------------------------------------------------------------------------------------


END






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG









--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[SM_DataToNext] (
                              @Current_YYYYMM   varchar(20),   --传入当前会计期间
                              @IsSuccess         int output     ---返回成功  -- 0 不成功  --1 
                            )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
Begin transaction SMDataToNext
   declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月
   declare  @SQLSTR         varchar(8000)  -- 下一个会计年月


declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。


declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)

declare @YYYYMMBILL int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @CLIENTID varchar(15)               --明细存货
declare @VENDORID varchar(15)               --明细存货编号
declare @YunShuDWID varchar(15)               --明细存货编号
declare @BANKID varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @Bqty NUMERIC(20,10)                          --数量
declare @BAMOUNT NUMERIC(20,10)                          --数量
declare @MBQTY NUMERIC(20,10)                          --数量
declare @MEQTY NUMERIC(20,10)                          --数量
declare @Eqty NUMERIC(20,10)                          --数量
declare @EAMOUNT NUMERIC(20,10)                          --数量
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @B_ID INTEGER


if substring(@Current_YYYYMM,5,2) = '12'  --- 如果当前会计月等于最大的会计月，将需要转入下年的的第一个会计年月
begin
    set @Next_YYYYMM   = convert(varchar,convert(int,substring(@Current_YYYYMM,1,4))+1) +'01'  
end
else
begin
    set @Next_YYYYMM   = substring(@Current_YYYYMM,1,4) +substring('00',1,2-len(convert(varchar,convert(int,substring(@Current_YYYYMM,5,2))+1)))+convert(varchar,convert(int,substring(@Current_YYYYMM,5,2))+1)
end


--判断当前会计期间是否月结，不能重复月结

declare @flagreturn int 
exec STORE_YYYYMM_INSERT   @flagreturn output 


--------取得接转当前会计期间的数据并复制到临时表中 begin --------------------------------
delete  DETAILBILLFLOWTMP

----------------------------------------------------
		SELECT @SQLSTR='	 select DISTINCT I.YYYYMM,I.GOODSID,    I.STOREID,  INF_COSTINGTYPEID,YYYYMMBILL,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0) as BQTY, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0) as MBQTY, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0) as BAMOUNT, ' --期初金额
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)+ isnull(E.INQTY,0) '
		SELECT @SQLSTR=@SQLSTR+'  as EQTY ,' --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0) '
		SELECT @SQLSTR=@SQLSTR+'  as MEQTY ,' --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0)  '
                           SELECT @SQLSTR=@SQLSTR+'  as EAMOUNT    '--期初金额
		 SELECT @SQLSTR=@SQLSTR+'   from DETAILBILLFLOW  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,STOREID,sum(INQTY*INOUTFLAG)  as INQTY ,sum(MINQTY*INOUTFLAG)  as MINQTY ,sum(INQTY*INOUTFLAG*INPRICE)  as INAMOUNT '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM = '+char(39)+@Current_YYYYMM+char(39)                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID,STOREID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID    AND E.STOREID = I.STOREID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,STOREID,sum(BQTY) as BQTY ,sum(MBQTY) as MBQTY,SUM(BAMOUNT)  AS BAMOUNT '
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM ='+char(39)+@Current_YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID,STOREID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID    AND B.STOREID = I.STOREID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where   YYYYMM='+char(39)+@Current_YYYYMM+char(39)  +'  AND   YYYYMMBILL = 0'
		SELECT @SQLSTR=@SQLSTR+'          order by  I.GOODSID,I.STOREID           '
------------------------------------------------------------------------

		PRINT @SQLSTR
                       INSERT  INTO   DETAILBILLFLOWTMP (YYYYMM,GOODSID,STOREID,INF_COSTINGTYPEID,YYYYMMBILL,BQTY,MBQTY,BAMOUNT,EQTY,MEQTY,EAMOUNT)   EXEC(@SQLSTR)

update   DETAILBILLFLOWTMP  set YYYYMM=@Next_YYYYMM
update   DETAILBILLFLOWTMP  set BQTY=EQTY
update   DETAILBILLFLOWTMP  set MBQTY=MEQTY
update   DETAILBILLFLOWTMP  set BAMOUNT=EAMOUNT
           ---定义游标解决插入的ID问题

    declare SM_Consign_DATANEXT Cursor READ_ONLY for Select   YYYYMM,GOODSID,STOREID,INF_COSTINGTYPEID,YYYYMMBILL,BQTY,BAMOUNT,EQTY,EAMOUNT,MBQTY,MEQTY   from DETAILBILLFLOWTMP 

    Open SM_Consign_DATANEXT

    fetch SM_Consign_DATANEXT into @YYYYMM,@GOODSID,@STOREID,@INF_COSTINGTYPEID,@YYYYMMBILL,@BQTY,@BAMOUNT,@EQTY,@EAMOUNT,@MBQTY,@MEQTY

    while @@fetch_status = 0            ----开始
    begin
             		    execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
		    insert into DetailBillFlow 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLCODE,ITEMNO,GOODSID,
		     BQTY,BPRICE,BAMOUNT,INQTY,INPRICE,OUTQTY,OUTPRICE,MBQTY,MEQTY,
		     EQTY,EPRICE,EAMOUNT,STOREID,CACULATEFLAG,INOUTFLAG,DIFAMOUNT,INF_COSTINGTYPEID,
		     BATCHREFID,REFQTY,REFCOUNT )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillCode,@itemNo,@GoodsID,
		     @BQTY,0,@BAMOUNT,0,0,Null,Null,@MBQTY,@MEQTY,
		     @EQTY,@price,@EAMOUNT,@StoreID,'F',@inoutFlag,null,@INF_COSTINGTYPEID,
		     @B_ID,0,0   )    
    fetch SM_Consign_DATANEXT into @YYYYMM,@GOODSID,@STOREID,@INF_COSTINGTYPEID,@YYYYMMBILL,@BQTY,@BAMOUNT,@EQTY,@EAMOUNT,@MBQTY,@MEQTY

    END           ------- SM_Consign_DATANEXT  WHILE

    close SM_Consign_DATANEXT
    deallocate SM_Consign_DATANEXT


-----------------------------------------------------------------------

----------结转YYYYMMBILL=2的月结记录

	delete DETAILBILLFLOWTMP

	select @SQLSTR ='INSERT  INTO   DETAILBILLFLOWTMP Select * from  DETAILBILLFLOW where EQTY >0  AND YYYYMMBILL=2 and YYYYMM='

	select @SQLSTR =@SQLSTR+Char(39)+@Current_YYYYMM+Char(39)

	EXEC (@SQLSTR)


				
        update   DETAILBILLFLOWTMP  set YYYYMM=@Next_YYYYMM,StoreEqty=EQTY,STOREEPrice=Eprice,StoreEAMOUNT=EAMOUNT,INQTY=EQTY,INPRICE=EPRICE

	update   DETAILBILLFLOWTMP  set  ID = YYYYMM+GOODSID+BILLID+ITEMNO+CAST(BILLTYPE AS char(3))


	INSERT  INTO   DETAILBILLFLOW Select * from  DETAILBILLFLOWTMP



-----------------------------------------------------------------------
		SELECT @SQLSTR='	 select  distinct I.YYYYMM,I.GOODSID,I.STOREID,  '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0) as BQTY, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0) as MBQTY, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0) as BAMOUNT, ' --期初金额
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)+ isnull(E.INQTY,0) '
		SELECT @SQLSTR=@SQLSTR+'  as EQTY ,' --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0) '
		SELECT @SQLSTR=@SQLSTR+'  as MEQTY ,' --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0)  '
                           SELECT @SQLSTR=@SQLSTR+'  as EAMOUNT '--期初金额
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,STOREID,sum(INQTY*INOUTFLAG)  as INQTY ,sum(MINQTY*INOUTFLAG)  as MINQTY ,sum(INQTY*INOUTFLAG*INPRICE)  as INAMOUNT'             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM = '+char(39)+@Current_YYYYMM+char(39)                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID ,STOREID'
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID   AND  E.STOREID = I.STOREID '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,STOREID,sum(BQTY) as BQTY,sum(MBQTY) as MBQTY ,SUM(BAMOUNT)  AS BAMOUNT'
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM ='+char(39)+@Current_YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID,STOREID '	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID    AND  B.STOREID = I.STOREID'
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where   YYYYMM='+char(39)+@Current_YYYYMM+char(39)  +'  AND   YYYYMMBILL = 0'
		SELECT @SQLSTR=@SQLSTR+'          order by  I.GOODSID ,I.STOREID      '
                        DELETE   GOODSINITTMP
                       INSERT  INTO  GOODSINITTMP (YYYYMM,GOODSID,STOREID,BQTY,MBQTY,BAMOUNT,EQTY,MEQTY,EAMOUNT)   EXEC(@SQLSTR)
                      UPDATE  GOODSINITTMP SET YYYYMM=@Next_YYYYMM,BAMOUNT=EAMOUNT,BQTY=EQTY,MBQTY=MEQTY
                      UPDATE  GOODSINITTMP SET BQTY=0    where  BQTY is null
                      UPDATE  GOODSINITTMP SET MBQTY=0    where  MBQTY is null
                      UPDATE  GOODSINITTMP SET BPRICE = BAMOUNT/BQTY   WHERE  NOT (BQTY=0)
                      INSERT INTO GOODSINIT  
                                 SELECT *  FROM  GOODSINITTMP

------------------------------------------------------以上是接转仓库与货品，以下接转是客户的应收帐款的问题。


delete  CLIENTBILLFLOWTMP

		SELECT @SQLSTR='	 select  I.YYYYMM,I.CLIENTID,  YYYYMMBILL,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0) as BAMOUNT, ' --期初金额
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0)  '
                           SELECT @SQLSTR=@SQLSTR+'  as EAMOUNT '--期初金额
		 SELECT @SQLSTR=@SQLSTR+' from CLIENTBILLFLOW  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select CLIENTID,sum(INAMOUNT*INOUTFLAG)  as INAMOUNT  '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from CLIENTBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM = '+char(39)+@Current_YYYYMM+char(39)                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by CLIENTID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.CLIENTID = I.CLIENTID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select CLIENTID,SUM(BAMOUNT)  AS BAMOUNT'
		SELECT @SQLSTR=@SQLSTR+' from CLIENTBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM ='+char(39)+@Current_YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by CLIENTID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.CLIENTID = I.CLIENTID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where   YYYYMM='+char(39)+@Current_YYYYMM+char(39)  +'  AND   YYYYMMBILL = 0'
		SELECT @SQLSTR=@SQLSTR+'          order by  I.CLIENTID                '
------------------------------------------------------------------------

                       INSERT  INTO   CLIENTBILLFLOWTMP (YYYYMM,CLIENTID,YYYYMMBILL,BAMOUNT,EAMOUNT)   EXEC(@SQLSTR)


update   CLIENTBILLFLOWTMP  set YYYYMM=@Next_YYYYMM
update   CLIENTBILLFLOWTMP  set BAMOUNT=EAMOUNT


           ---定义游标解决插入的ID问题

    declare SM_Consign_CLIENT Cursor READ_ONLY for Select   YYYYMM,CLIENTID,YYYYMMBILL,BAMOUNT,EAMOUNT
						    from CLIENTBILLFLOWTMP 

    Open SM_Consign_CLIENT

    fetch SM_Consign_CLIENT into @YYYYMM,@CLIENTID,@YYYYMMBILL,@BAMOUNT,@EAMOUNT

    while @@fetch_status = 0            ----开始
    begin
             		    execute  GETKEYVALUE     'CLIENTBillFlow',@R_KeyValue = @NEWID output
		    insert into CLIENTBillFlow 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLCODE,CLIENTID,
		     BAMOUNT,     CACULATEFLAG,INOUTFLAG,EAMOUNT     )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillCode,@CLIENTID,
		     @BAMOUNT,    'F',@inoutFlag,@EAMOUNT    )    
    fetch SM_Consign_CLIENT into @YYYYMM,@CLIENTID,@YYYYMMBILL,@BAMOUNT,@EAMOUNT

    END           ------- SM_Consign_CLIENT  WHILE

    close SM_Consign_CLIENT
    deallocate SM_Consign_CLIENT

  update   accoptionS  set optionvalue=@Next_YYYYMM           where optionname ='YYYYMM'
     
------------------------------------------以下是接转供应商
delete  VENDORBILLFLOWTMP

		SELECT @SQLSTR='	 select  I.YYYYMM,I.VENDORID,  YYYYMMBILL,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0) as BAMOUNT, ' --期初金额
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0)  '
                           SELECT @SQLSTR=@SQLSTR+'  as EAMOUNT '--期初金额
		 SELECT @SQLSTR=@SQLSTR+' from VENDORBILLFLOW  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select VENDORID,sum(INAMOUNT*INOUTFLAG)  as INAMOUNT  '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from VENDORBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM = '+char(39)+@Current_YYYYMM+char(39)                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by VENDORID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.VENDORID = I.VENDORID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select VENDORID,SUM(BAMOUNT)  AS BAMOUNT'
		SELECT @SQLSTR=@SQLSTR+' from VENDORBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM ='+char(39)+@Current_YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by VENDORID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.VENDORID = I.VENDORID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where   YYYYMM='+char(39)+@Current_YYYYMM+char(39)  +'  AND   YYYYMMBILL = 0'
		SELECT @SQLSTR=@SQLSTR+'          order by  I.VENDORID                '
------------------------------------------------------------------------

                       INSERT  INTO   VENDORBILLFLOWTMP (YYYYMM,VENDORID,YYYYMMBILL,BAMOUNT,EAMOUNT)   EXEC(@SQLSTR)


update   VENDORBILLFLOWTMP  set YYYYMM=@Next_YYYYMM
update   VENDORBILLFLOWTMP  set BAMOUNT=EAMOUNT


           ---定义游标解决插入的ID问题

    declare SM_Consign_VENDOR Cursor  READ_ONLY for Select   YYYYMM,VENDORID,YYYYMMBILL,BAMOUNT,EAMOUNT
						    from VENDORBILLFLOWTMP 

    Open SM_Consign_VENDOR

    fetch SM_Consign_VENDOR into @YYYYMM,@VENDORID,@YYYYMMBILL,@BAMOUNT,@EAMOUNT

    while @@fetch_status = 0            ----开始
    begin
             		    execute  GETKEYVALUE     'VENDORBillFlow',@R_KeyValue = @NEWID output
		    insert into VENDORBillFlow 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLCODE,VENDORID,
		     BAMOUNT,     CACULATEFLAG,INOUTFLAG,EAMOUNT     )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillCode,@VENDORID,
		     @BAMOUNT,    'F',@inoutFlag,@EAMOUNT    )    
    fetch SM_Consign_VENDOR into @YYYYMM,@VENDORID,@YYYYMMBILL,@BAMOUNT,@EAMOUNT

    END           ------- SM_Consign_VENDOR  WHILE

    close SM_Consign_VENDOR
    deallocate SM_Consign_VENDOR
           ---定义游标解决插入的ID问题



------------------------------------------以下是接转运输单位
delete  YunShuDWBILLFLOWTMP

		SELECT @SQLSTR='	 select  I.YYYYMM,I.YunShuDWID,  YYYYMMBILL,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0) as BAMOUNT, ' --期初金额
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0)  '
                           SELECT @SQLSTR=@SQLSTR+'  as EAMOUNT '--期初金额
		 SELECT @SQLSTR=@SQLSTR+' from YunShuDWBILLFLOW  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select YunShuDWID,sum(INAMOUNT*INOUTFLAG)  as INAMOUNT  '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from YunShuDWBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM = '+char(39)+@Current_YYYYMM+char(39)                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by YunShuDWID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.YunShuDWID = I.YunShuDWID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select YunShuDWID,SUM(BAMOUNT)  AS BAMOUNT'
		SELECT @SQLSTR=@SQLSTR+' from YunShuDWBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM ='+char(39)+@Current_YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by YunShuDWID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.YunShuDWID = I.YunShuDWID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where   YYYYMM='+char(39)+@Current_YYYYMM+char(39)  +'  AND   YYYYMMBILL = 0'
		SELECT @SQLSTR=@SQLSTR+'          order by  I.YunShuDWID                '
------------------------------------------------------------------------

                       INSERT  INTO   YunShuDWBILLFLOWTMP (YYYYMM,YunShuDWID,YYYYMMBILL,BAMOUNT,EAMOUNT)   EXEC(@SQLSTR)


update   YunShuDWBILLFLOWTMP  set YYYYMM=@Next_YYYYMM
update   YunShuDWBILLFLOWTMP  set BAMOUNT=EAMOUNT


           ---定义游标解决插入的ID问题

    declare SM_Consign_YunShuDW Cursor  READ_ONLY for Select   YYYYMM,YunShuDWID,YYYYMMBILL,BAMOUNT,EAMOUNT
						    from YunShuDWBILLFLOWTMP 

    Open SM_Consign_YunShuDW

    fetch SM_Consign_YunShuDW into @YYYYMM,@YunShuDWID,@YYYYMMBILL,@BAMOUNT,@EAMOUNT

    while @@fetch_status = 0            ----开始
    begin
             		    execute  GETKEYVALUE     'YunShuDWBillFlow',@R_KeyValue = @NEWID output
		    insert into YunShuDWBillFlow 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLCODE,YunShuDWID,
		     BAMOUNT,     CACULATEFLAG,INOUTFLAG,EAMOUNT     )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillCode,@YunShuDWID,
		     @BAMOUNT,    'F',@inoutFlag,@EAMOUNT    )    
    fetch SM_Consign_YunShuDW into @YYYYMM,@YunShuDWID,@YYYYMMBILL,@BAMOUNT,@EAMOUNT

    END           ------- SM_Consign_YunShuDW  WHILE

    close SM_Consign_YunShuDW
    deallocate SM_Consign_YunShuDW
           ---定义游标解决插入的ID问题


------------------------------------------以下是接转银行帐目
delete  BANKBILLFLOWTMP

		SELECT @SQLSTR='	 select  I.YYYYMM,I.BANKID,  YYYYMMBILL,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0) as BAMOUNT, ' --期初金额
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0)  '
                           SELECT @SQLSTR=@SQLSTR+'  as EAMOUNT '--期初金额
		 SELECT @SQLSTR=@SQLSTR+' from BANKBILLFLOW  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select BANKID,sum(INAMOUNT*INOUTFLAG)  as INAMOUNT  '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from BANKBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM = '+char(39)+@Current_YYYYMM+char(39)                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by BANKID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.BANKID = I.BANKID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select BANKID,SUM(BAMOUNT)  AS BAMOUNT'
		SELECT @SQLSTR=@SQLSTR+' from BANKBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM ='+char(39)+@Current_YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by BANKID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.BANKID = I.BANKID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where   YYYYMM='+char(39)+@Current_YYYYMM+char(39)  +'  AND   YYYYMMBILL = 0'
		SELECT @SQLSTR=@SQLSTR+'          order by  I.BANKID                '
------------------------------------------------------------------------

                       INSERT  INTO   BANKBILLFLOWTMP (YYYYMM,BANKID,YYYYMMBILL,BAMOUNT,EAMOUNT)   EXEC(@SQLSTR)


update   BANKBILLFLOWTMP  set YYYYMM=@Next_YYYYMM
update   BANKBILLFLOWTMP  set BAMOUNT=EAMOUNT


           ---定义游标解决插入的ID问题

    declare SM_Consign_BANK Cursor READ_ONLY for Select   YYYYMM,BANKID,YYYYMMBILL,BAMOUNT,EAMOUNT
						    from BANKBILLFLOWTMP 

    Open SM_Consign_BANK

    fetch SM_Consign_BANK into @YYYYMM,@BANKID,@YYYYMMBILL,@BAMOUNT,@EAMOUNT

    while @@fetch_status = 0            ----开始
    begin
             		    execute  GETKEYVALUE     'BANKBillFlow',@R_KeyValue = @NEWID output
		    insert into BANKBillFlow 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLCODE,BANKID,
		     BAMOUNT,     CACULATEFLAG,INOUTFLAG,EAMOUNT     )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillCode,@BANKID,
		     @BAMOUNT,    'F',@inoutFlag,@EAMOUNT    )    
    fetch SM_Consign_BANK into @YYYYMM,@BANKID,@YYYYMMBILL,@BAMOUNT,@EAMOUNT

    END           ------- SM_Consign_BANK  WHILE

    close SM_Consign_BANK
    deallocate SM_Consign_BANK
           ---定义游标解决插入的ID问题

---------------------------------------处理下个月已经存在的业务进行重算
------2005.10.29加入

    declare SM_Consign_BANK_next Cursor for Select   BANKID    from BANKBILLFLOW   WHERE YYYYMMBILL=1  AND YYYYMM=@Next_YYYYMM

    Open SM_Consign_BANK_next

    fetch SM_Consign_BANK_next into   @BANKID

    while @@fetch_status = 0            ----开始
    begin
                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@Next_YYYYMM

    fetch SM_Consign_BANK_next into @BANKID

    END           ------- SM_Consign_BANK_next  WHILE

    close SM_Consign_BANK_next
    deallocate SM_Consign_BANK_next
           ---定义游标解决插入的ID问题

------------------------
    declare SM_Consign_VENDOR_next Cursor READ_ONLY for Select   VENDORID    from VENDORBILLFLOW   WHERE YYYYMMBILL=1  AND YYYYMM=@Next_YYYYMM

    Open SM_Consign_VENDOR_next

    fetch SM_Consign_VENDOR_next into   @VENDORID

    while @@fetch_status = 0            ----开始
    begin
                            execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@Next_YYYYMM

    fetch SM_Consign_VENDOR_next into @VENDORID

    END           ------- SM_Consign_VENDOR_next  WHILE

    close SM_Consign_VENDOR_next
    deallocate SM_Consign_VENDOR_next
           ---定义游标解决插入的ID问题

    declare SM_Consign_CLIENT_next Cursor for Select   CLIENTID    from CLIENTBILLFLOW   WHERE YYYYMMBILL=1  AND YYYYMM=@Next_YYYYMM

    Open SM_Consign_CLIENT_next

    fetch SM_Consign_CLIENT_next into   @CLIENTID

    while @@fetch_status = 0            ----开始
    begin
                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@Next_YYYYMM

    fetch SM_Consign_CLIENT_next into @CLIENTID

    END           ------- SM_Consign_CLIENT_next  WHILE

    close SM_Consign_CLIENT_next
    deallocate SM_Consign_CLIENT_next
           ---定义游标解决插入的ID问题
----------------------------------

	declare @STOREHSFS   INTEGER  --分仓核算

	       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           


    declare SM_GOODS_next Cursor for Select   GOODSID,STOREID    from   DETAILBILLFLOW   WHERE YYYYMMBILL=1  AND YYYYMM=@Next_YYYYMM  AND  CACULATEFLAG='T' 

    Open SM_GOODS_next

    fetch SM_GOODS_next into   @GOODSID,@STOREID

    while @@fetch_status = 0            ----开始
    begin
       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID

                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@Next_YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@Next_YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@Next_YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@Next_YYYYMM
				     END

                            END



    fetch SM_GOODS_next into   @GOODSID,@STOREID

    END           ------- SM_GOODS_next  WHILE

    close SM_GOODS_next
    deallocate SM_GOODS_next
           ---定义游标解决插入的ID问题
----------------------------------









-------------------2005.10.29

--------------------------------------

  update   accoptionS  set optionvalue=@Next_YYYYMM           where optionname ='YYYYMM'
     


--------取得接转当前会计期间的数据并复制到临时表中 end ------------------------------------

--写结转信息
  If @@error = 0
  begin
     commit transaction SMDataToNext
   set @IsSuccess=1
  end
  else
  begin
    rollback transaction SMDataToNext
   set @IsSuccess=0
    raiserror('结转失败 ', 1, 20) 
  end







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG















CREATE PROCEDURE SM_DataToNextDel (
                              @Current_YYYYMM   varchar(20),   --传入当前会计期间
                              @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                              @IsSuccess         int output     ---返回成功  -- 0 不成功  --1 
                            )  --APSOFTENCRYPTION       WITH ENCRYPTION
 AS 
Begin transaction SMDataToNext

   declare  @PREV_YYYYMM          varchar(6)  -- 上一个会计年月
   declare  @GOODSID          varchar(10)  -- 上一个会计年月
   declare  @STOREID         varchar(10)  -- 上一个会计年月
   declare  @CLIENTID         varchar(10)  -- 上一个会计年月
   declare  @YunShuDWID         varchar(10)  -- 上一个会计年月
   declare  @VENDORID         varchar(10)  -- 上一个会计年月
   declare  @BANKID         varchar(10)  -- 上一个会计年月
   declare  @BILLID          varchar(10)  -- 上一个会计年月

      SET @RETURNSTRING='  '

	if substring(@Current_YYYYMM,5,2) = '01'  --- 如果当前会计月等于最大的会计月，将需要转入下年的的第一个会计年月
	begin
	    set @PREV_YYYYMM   = convert(varchar,convert(int,substring(@Current_YYYYMM,1,4))-1) +'12'  
	end
	else
	begin
	    set @PREV_YYYYMM   = substring(@Current_YYYYMM,1,4) +substring('00',1,2-len(convert(varchar,convert(int,substring(@Current_YYYYMM,5,2))-1)))+convert(varchar,convert(int,substring(@Current_YYYYMM,5,2))-1)
	end

		            IF  NOT  exists (select * from  DETAILBILLFLOW    where     YYYYMMBILL = 0  AND  YYYYMM =@PREV_YYYYMM  )
			BEGIN
			      rollback transaction SMDataToNext
			      set @IsSuccess = 0
                                              SET @RETURNSTRING='因为本会计期间是启用帐套的月份，不允许取消月末结帐'
                                          RETURN
			END

         	 DELETE  DETAILBILLFLOW  where YYYYMM=@Current_YYYYMM   and  YYYYMMBILL = 0   
  
         	 DELETE  DETAILBILLFLOW  where YYYYMM=@Current_YYYYMM   and  YYYYMMBILL = 2   AND len(ID)>10

	delete     GOODSINIT  where YYYYMM=@Current_YYYYMM   ---------这个不处理不影响数据
---------------------------------------------
		delete  CLIENTBILLFLOWTMP

		INSERT INTO  CLIENTBILLFLOWTMP   
	            select  * FROM CLIENTBILLFLOW  where YYYYMM=@Current_YYYYMM   and  YYYYMMBILL = 0   

		    declare CLIENT_Consign Cursor for   SELECT DISTINCT CLIENTID,BILLID FROM CLIENTBILLFLOWTMP 


		    Open CLIENT_Consign

		    fetch CLIENT_Consign into @CLIENTID,@BILLID

		    while @@fetch_status = 0            ----开始
		    begin
		            IF exists (select * from  CLIENTBILLFLOW where  CLIENTID=@CLIENTID  AND YYYYMMBILL = 0  AND  YYYYMM =@PREV_YYYYMM  )
		            BEGIN

		          	 DELETE  CLIENTBILLFLOW  where YYYYMM=@Current_YYYYMM   and  YYYYMMBILL = 0   AND   CLIENTID=@CLIENTID 

			END

		    fetch CLIENT_Consign into @CLIENTID,@BILLID

		    END           ------- CLIENT_Consign  WHILE

		    close CLIENT_Consign
		    deallocate CLIENT_Consign
  
-----------------------------------------
		delete  VENDORBILLFLOWTMP

		INSERT INTO  VENDORBILLFLOWTMP   
	            select  * FROM VENDORBILLFLOW  where YYYYMM=@Current_YYYYMM   and  YYYYMMBILL = 0   

		    declare VENDOR_Consign Cursor for   SELECT DISTINCT VENDORID,BILLID FROM VENDORBILLFLOWTMP 


		    Open VENDOR_Consign

		    fetch VENDOR_Consign into @VENDORID,@BILLID

		    while @@fetch_status = 0            ----开始
		    begin
		            IF exists (select * from  VENDORBILLFLOW where  VENDORID=@VENDORID  AND YYYYMMBILL = 0  AND  YYYYMM =@PREV_YYYYMM  )
		            BEGIN

		          	 DELETE  VENDORBILLFLOW  where YYYYMM=@Current_YYYYMM   and  YYYYMMBILL = 0   AND   VENDORID=@VENDORID 

			END

		    fetch VENDOR_Consign into @VENDORID,@BILLID

		    END           ------- VENDOR_Consign  WHILE

		    close VENDOR_Consign
		    deallocate VENDOR_Consign
  
-----------------------------------------

		delete  YunShuDWBILLFLOWTMP

		INSERT INTO  YunShuDWBILLFLOWTMP   
	            select  * FROM YunShuDWBILLFLOW  where YYYYMM=@Current_YYYYMM   and  YYYYMMBILL = 0   

		    declare YunShuDW_Consign Cursor for   SELECT DISTINCT YunShuDWID,BILLID FROM YunShuDWBILLFLOWTMP 


		    Open YunShuDW_Consign

		    fetch YunShuDW_Consign into @YunShuDWID,@BILLID

		    while @@fetch_status = 0            ----开始
		    begin
		            IF exists (select * from  YunShuDWBILLFLOW where  YunShuDWID=@YunShuDWID  AND YYYYMMBILL = 0  AND  YYYYMM =@PREV_YYYYMM  )
		            BEGIN

		          	 DELETE  YunShuDWBILLFLOW  where YYYYMM=@Current_YYYYMM   and  YYYYMMBILL = 0   AND   YunShuDWID=@YunShuDWID 

			END

		    fetch YunShuDW_Consign into @YunShuDWID,@BILLID

		    END           ------- YunShuDW_Consign  WHILE

		    close YunShuDW_Consign
		    deallocate YunShuDW_Consign


-----------------------------------------

		delete  BANKBILLFLOWTMP

		INSERT INTO  BANKBILLFLOWTMP   
	            select  * FROM BANKBILLFLOW  where YYYYMM=@Current_YYYYMM   and  YYYYMMBILL = 0   

		    declare BANK_Consign Cursor for   SELECT DISTINCT BANKID,BILLID FROM BANKBILLFLOWTMP 


		    Open BANK_Consign

		    fetch BANK_Consign into @BANKID,@BILLID

		    while @@fetch_status = 0            ----开始
		    begin
		            IF exists (select * from  BANKBILLFLOW where  BANKID=@BANKID  AND YYYYMMBILL = 0  AND  YYYYMM =@PREV_YYYYMM  )
		            BEGIN

		          	 DELETE  BANKBILLFLOW  where YYYYMM=@Current_YYYYMM   and  YYYYMMBILL = 0   AND   BANKID=@BANKID 

			END

		    fetch BANK_Consign into @BANKID,@BILLID

		    END           ------- BANK_Consign  WHILE

		    close BANK_Consign
		    deallocate BANK_Consign
  
  update   accoptionS  set optionvalue=@PREV_YYYYMM        where optionname ='YYYYMM'



--------取得接转当前会计期间的数据并复制到临时表中 end ------------------------------------

--写结转信息
  If @@error = 0
  begin
     commit transaction SMDataToNext
   set @IsSuccess=1
  end
  else
  begin
    rollback transaction SMDataToNext
   set @IsSuccess=0
    raiserror('结转失败 ', 1, 20) 
  end



----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













-------------------------------------------------------------------

CREATE PROCEDURE SM_Data_START (
                              @START_YYYYMM   varchar(20),   --传入当前会计期间
                              @START_YYYYMMDD  DATETIME,   --传入当前时间
                              @IsSuccess         int output     ---返回成功  -- 0 不成功  --1 
                            )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
Begin transaction SMDataToNext
   declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月
   declare  @SQLSTR         varchar(8000)  -- 下一个会计年月


declare @YYYYMM varchar(6)                   --会计年月     
declare @Current_YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。


declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)

declare @bill_type int           ---单据类型
declare @YYYYMMBILL int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @VENDORID varchar(15)               --明细存货编号
declare @CLIENTID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @Bqty NUMERIC(20,10)                          --数量
declare @BAMOUNT NUMERIC(20,10)                          --数量
declare @Eqty NUMERIC(20,10)                          --数量
declare @MEqty NUMERIC(20,10)                          --数量
declare @MBqty NUMERIC(20,10)                          --数量
declare @EAMOUNT NUMERIC(20,10)                          --数量
declare @BEGINAMOUNT NUMERIC(20,10)                          --数量

declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BANKID VARCHAR(25)
declare @YunShuDWID VARCHAR(25)
declare @BILLDATE DATEtime
declare @B_ID INTEGER
declare  @STATUS INTEGER
  


                 SELECT  @Current_YYYYMM='199912'
	    set @Next_YYYYMM   = @START_YYYYMM
         	SET @STATUS =(select   STATUS   FROM  ACCINFO  WHERE GUID='0001')
            IF  @STATUS=1                      ----已经启用帐套
             BEGIN
	     commit transaction SMDataToNext         
	   	   set @IsSuccess=1
	             RETURN
             END

--判断当前会计期间是否月结，不能重复月结



--------取得接转当前会计期间的数据并复制到临时表中 begin --------------------------------
delete  DETAILBILLFLOWTMP

		SELECT @SQLSTR='	 select DISTINCT I.YYYYMM,I.GOODSID,  I.STOREID,  INF_COSTINGTYPEID,YYYYMMBILL,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0) as BQTY, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0) as MBQTY, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0) as BAMOUNT, ' --期初金额
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)+ isnull(E.INQTY,0) '
		SELECT @SQLSTR=@SQLSTR+'  as EQTY ,' --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0) '
		SELECT @SQLSTR=@SQLSTR+'  as MEQTY ,' --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0)  '
                           SELECT @SQLSTR=@SQLSTR+'  as EAMOUNT '--期初金额
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,STOREID,sum(INQTY*INOUTFLAG)  as INQTY  ,sum(MINQTY*INOUTFLAG)  as MINQTY ,sum(INQTY*INOUTFLAG*INPRICE)  as INAMOUNT'             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM = '+char(39)+@Current_YYYYMM+char(39)                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID,STOREID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID    AND E.STOREID = I.STOREID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,STOREID,sum(BQTY) as BQTY ,sum(MBQTY) as MBQTY ,SUM(BAMOUNT)  AS BAMOUNT'
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM ='+char(39)+@Current_YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID,STOREID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID     AND B.STOREID = I.STOREID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where   YYYYMM='+char(39)+@Current_YYYYMM+char(39)  +'  AND   YYYYMMBILL = 0'
		SELECT @SQLSTR=@SQLSTR+'          order by  I.GOODSID,I.STOREID           '
------------------------------------------------------------------------

                       INSERT  INTO   DETAILBILLFLOWTMP (YYYYMM,GOODSID,STOREID,INF_COSTINGTYPEID,YYYYMMBILL,BQTY,MBQTY,BAMOUNT,EQTY,MEQTY,EAMOUNT)   EXEC(@SQLSTR)


update   DETAILBILLFLOWTMP  set YYYYMM=@Next_YYYYMM
update   DETAILBILLFLOWTMP  set BQTY=EQTY
update   DETAILBILLFLOWTMP  set MBQTY=MEQTY
update   DETAILBILLFLOWTMP  set BAMOUNT=EAMOUNT
           ---定义游标解决插入的ID问题

    declare SM_Consign_DATANEXT Cursor for Select   YYYYMM,GOODSID,STOREID,INF_COSTINGTYPEID,YYYYMMBILL,BQTY,MBQTY,BAMOUNT,EQTY,MEQTY,EAMOUNT
						    from DETAILBILLFLOWTMP 

    Open SM_Consign_DATANEXT

    fetch SM_Consign_DATANEXT into @YYYYMM,@GOODSID,@STOREID,@INF_COSTINGTYPEID,@YYYYMMBILL,@BQTY,@MBQTY,@BAMOUNT,@EQTY,@MEQTY,@EAMOUNT

    while @@fetch_status = 0            ----开始
    begin

             		    execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
		    insert into DetailBillFlow 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLCODE,ITEMNO,GOODSID,
		     BQTY,BPRICE,BAMOUNT,INQTY,INPRICE,OUTQTY,OUTPRICE,MBQTY,MEQTY,
		     EQTY,EPRICE,EAMOUNT,STOREID,CACULATEFLAG,INOUTFLAG,DIFAMOUNT,INF_COSTINGTYPEID,
		     BATCHREFID,REFQTY,REFCOUNT )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillCode,@itemNo,@GoodsID,
		     @BQTY,0,@BAMOUNT,0,0,Null,Null,@MBQTY,@MEQTY,
		     @EQTY,@price,@EAMOUNT,@StoreID,'F',@inoutFlag,null,@INF_COSTINGTYPEID,
		     @B_ID,0,0  )    
    fetch SM_Consign_DATANEXT into @YYYYMM,@GOODSID,@STOREID,@INF_COSTINGTYPEID,@YYYYMMBILL,@BQTY,@MBQTY,@BAMOUNT,@EQTY,@MEQTY,@EAMOUNT

    END           ------- SM_Consign_DATANEXT  WHILE

    close SM_Consign_DATANEXT
    deallocate SM_Consign_DATANEXT
-------------------------------------------------------------



----------结转YYYYMMBILL=2的月结记录

	delete DETAILBILLFLOWTMP

	select @SQLSTR ='INSERT  INTO   DETAILBILLFLOWTMP Select * from  DETAILBILLFLOW where EQTY >0  AND YYYYMMBILL=2 and YYYYMM='

	select @SQLSTR =@SQLSTR+Char(39)+@Current_YYYYMM+Char(39)

	EXEC (@SQLSTR)

        update   DETAILBILLFLOWTMP  set YYYYMM=@Next_YYYYMM,StoreEqty=EQTY,STOREEPrice=Eprice,StoreEAMOUNT=EAMOUNT,INQTY=EQTY,INPRICE=EPRICE

	update   DETAILBILLFLOWTMP  set  ID = YYYYMM+GOODSID+BILLID+ITEMNO+CAST(BILLTYPE AS char(3))



	INSERT  INTO   DETAILBILLFLOW Select * from  DETAILBILLFLOWTMP



-----------------------------------------------------------------------
		SELECT @SQLSTR='	 select  DISTINCT I.YYYYMM,I.GOODSID, I.STOREID, '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0) as BQTY, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0) as MBQTY, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0) as BAMOUNT, ' --期初金额
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)+ isnull(E.INQTY,0) '
		SELECT @SQLSTR=@SQLSTR+'  as EQTY ,' --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0) '
		SELECT @SQLSTR=@SQLSTR+'  as MEQTY ,' --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0)  '
                           SELECT @SQLSTR=@SQLSTR+'  as EAMOUNT '--期初金额
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,STOREID,sum(INQTY*INOUTFLAG)  as INQTY ,sum(MINQTY*INOUTFLAG)  as MINQTY  ,sum(INQTY*INOUTFLAG*INPRICE)  as INAMOUNT'             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM = '+char(39)+@Current_YYYYMM+char(39)                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID ,STOREID'
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID    AND  E.STOREID = I.STOREID '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,STOREID,sum(BQTY) as BQTY ,sum(MBQTY) as MBQTY,SUM(BAMOUNT)  AS BAMOUNT'
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM ='+char(39)+@Current_YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID,STOREID '	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID    AND  B.STOREID = I.STOREID '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where   YYYYMM='+char(39)+@Current_YYYYMM+char(39)  +'  AND   YYYYMMBILL = 0'
		SELECT @SQLSTR=@SQLSTR+'          order by  I.GOODSID,I.STOREID       '
                        DELETE   GOODSINITTMP
                       INSERT  INTO  GOODSINITTMP (YYYYMM,GOODSID,STOREID,BQTY,MBQTY,BAMOUNT,EQTY,MEQTY,EAMOUNT)   EXEC(@SQLSTR)
                      UPDATE  GOODSINITTMP SET YYYYMM=@START_YYYYMM,BAMOUNT=EAMOUNT,BQTY=EQTY,MBQTY=MEQTY
                      UPDATE  GOODSINITTMP SET BQTY=0    where  BQTY is null
                      UPDATE  GOODSINITTMP SET MBQTY=0    where  MBQTY is null
                      UPDATE  GOODSINITTMP SET BPRICE = BAMOUNT/BQTY   WHERE  NOT (BQTY=0)
                      INSERT INTO GOODSINIT  
                                 SELECT *  FROM  GOODSINITTMP
---------------------------------------以上是仓库初始化


    declare CLIENT_00 Cursor for Select   CLIENTID,BEGINAMOUNT from CLIENT 

    Open CLIENT_00

    fetch CLIENT_00 into   @CLIENTID,@BEGINAMOUNT
    while @@fetch_status = 0            ----开始
    begin

            IF   (not exists(select *  from CLIENTBILLFLOW  where 
             		                                    (rtrim(CLIENTID) = @CLIENTID)
                                        	      and(rtrim(YYYYMM) = @START_YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN

             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,'199912',1,@BillDate,@BillType,@CLIENTID,
		     0,@BEGINAMOUNT,Null,
		     1,@BEGINAMOUNT )    

             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@START_YYYYMM,0,@BillDate,@BillType,@CLIENTID,
		     @BEGINAMOUNT,0,Null,
		     1,@BEGINAMOUNT  )    
            END      ------IF   END
	    fetch CLIENT_00 into   @CLIENTID,@BEGINAMOUNT
       END

    close CLIENT_00
    deallocate CLIENT_00

----------------------------------------------------------------------------------
    declare VENDOR_00 Cursor for Select   VENDORID,BEGINAMOUNT from VENDOR 

    Open VENDOR_00

    fetch VENDOR_00 into   @VENDORID,@BEGINAMOUNT
    while @@fetch_status = 0            ----开始
    begin


            IF   (not exists(select *  from VENDORBILLFLOW  where 
             		                                    (rtrim(VENDORID) = @VENDORID)
                                        	      and(rtrim(YYYYMM) = @START_YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN
             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,'199912',1,@BillDate,@BillType,@VENDORID,
		     @BEGINAMOUNT,0,Null,
		     1,@BEGINAMOUNT  )    

             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@START_YYYYMM,0,@BillDate,@BillType,@VENDORID,
		     @BEGINAMOUNT,0,Null,
		     1,@BEGINAMOUNT  )    
            END      ------IF   END
-------------------------------增加应收帐款  是 INOUTFLAG为1
	    fetch VENDOR_00 into   @VENDORID,@BEGINAMOUNT
       END


    close VENDOR_00
    deallocate VENDOR_00

--------------------------------------

    declare BANK_00 Cursor for Select   BANKID,BEGINAMOUNT from BANK 

    Open BANK_00

    fetch BANK_00 into   @BANKID,@BEGINAMOUNT
    while @@fetch_status = 0            ----开始
    begin


            IF   (not exists(select *  from BANKBILLFLOW  where 
             		                                    (rtrim(BANKID) = @BANKID)
                                        	      and(rtrim(YYYYMM) = @START_YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,'199912',1,@BillDate,@BillType,@BANKID,
		     @BEGINAMOUNT,0,Null,
		     1,@BEGINAMOUNT  )    

             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@START_YYYYMM,0,@BillDate,@BillType,@BANKID,
		     @BEGINAMOUNT,0,Null,
		     1,@BEGINAMOUNT  )    
            END      ------IF   END
-------------------------------增加应收帐款  是 INOUTFLAG为1
	    fetch BANK_00 into   @BANKID,@BEGINAMOUNT
       END
--------------------------------------
    close BANK_00
    deallocate BANK_00


--------------------------------------

    declare YunShuDW_00 Cursor for Select   YunShuDWID,BEGINAMOUNT from YunShuDW 

    Open YunShuDW_00

    fetch YunShuDW_00 into   @YunShuDWID,@BEGINAMOUNT
    while @@fetch_status = 0            ----开始
    begin


            IF   (not exists(select *  from YunShuDWBILLFLOW  where 
             		                                    (rtrim(YunShuDWID) = @YunShuDWID)
                                        	      and(rtrim(YYYYMM) = @START_YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN
             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,'199912',1,@BillDate,@BillType,@YunShuDWID,
		     @BEGINAMOUNT,0,Null,
		     1,@BEGINAMOUNT  )    

             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@START_YYYYMM,0,@BillDate,@BillType,@YunShuDWID,
		     @BEGINAMOUNT,0,Null,
		     1,@BEGINAMOUNT  )    
            END      ------IF   END
-------------------------------增加应收帐款  是 INOUTFLAG为1
	    fetch YunShuDW_00 into   @YunShuDWID,@BEGINAMOUNT
       END
--------------------------------------
    close YunShuDW_00
    deallocate YunShuDW_00




  update   accoptionS  set optionvalue = @START_YYYYMM          where optionname ='YYYYMM'
  update   ACCINFO     set STARTDATE= @START_YYYYMMDD          where GUID ='0001'
  update   ACCINFO     set STATUS= 1          where GUID ='0001'
     



--------取得接转当前会计期间的数据并复制到临时表中 end ------------------------------------



--写结转信息
  If @@error = 0
  begin
     commit transaction SMDataToNext
   set @IsSuccess=1
  end
  else
  begin
    rollback transaction SMDataToNext
   set @IsSuccess=0
    raiserror('结转失败 ', 1, 20) 
  end








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











--------------------------------------------------------------------
--------------------------------------------------------------------
----------------------------------
---------2005.07.20   修改过
--------------------------------------------------------------------
CREATE PROCEDURE [dbo].[STOREINOUTMXBREP](@STOREID varchar(8) ,                        -----如果为0000则全部仓库
                                                                                            @Begin_Date   varchar(10) ,
                                                                                           @End_date   varchar(10) ,  
						           @LCODE  varchar(10),             ---如果LCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSCODE  varchar(20),             ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSNAME  varchar(20),         ---如果GOODSNAME  为‘GGGG’表示不对类别进行查询
                                                                                           @INF_COSTINGTYPEID   smallint  ,    --------同价调拨标志   0  代表 不作为过滤条件
						           @modelNAME  varchar(20)             ---如果modelNAME  为‘GGGG’表示不对类别进行查询
                        
                                                      )   --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @end_dateAddone  datetime,
        @MAXBILLDATE  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8),
        @MAXYYYYMM   varchar(8),
        @WHERESTING   varchar(1800),
        @WHERESTING00   varchar(1800),
        @STOREIDSTR   varchar(100)

declare @GOODSCODE00   varchar(50)
declare @GOODSNAME00  varchar(50)

declare @ID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare  @BILLTYPE  INTEGER
declare @GOODSID  nvarchar(50)
declare @GOODSID00  nvarchar(50)
declare @BILLCODE  nvarchar(50)
declare @SPECNAME  nvarchar(50)
declare @BILLDATE  datetime
declare @BILLTYPENAME  nvarchar(50)
declare @UNIT  nvarchar(50) 
declare @INQTY  NUMERIC(20,10)
declare @INPRICE  NUMERIC(20,10)
declare @INAMOUNT NUMERIC(20,10)
declare @OUTQTY  NUMERIC(20,10)
declare @MOUTQTY  NUMERIC(20,10)
declare @MBQTY  NUMERIC(20,10)
declare @MINQTY  NUMERIC(20,10)
declare @MEQTY  NUMERIC(20,10)
declare @OUTPRICE  NUMERIC(20,10)
declare @OUTAMOUNT NUMERIC(20,10)
declare @EQTY NUMERIC(20,10)
declare @EPRICE NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @EQTYPREV NUMERIC(20,10)
declare @MEQTYPREV NUMERIC(20,10)
declare @EPRICEPREV NUMERIC(20,10)
declare @EAMOUNTPREV NUMERIC(20,10)
---//==========
declare @BQTY  NUMERIC(20,10)
declare @BPRICE  NUMERIC(20,10)
declare @BAMOUNT NUMERIC(20,10)
declare @MAXID  nvarchar(50)

                   set @now_date=(select   max(billDATE)   FROM detailbillflow)
--@WHERESTR='  and 1=1 '


                          
		if     NOT (@LCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = '  AND   GOODSID IN ( select GOODSID from  GOODS  where Lcode like '+CHAR(39)+@LCODE+'%'+CHAR(39)+ ')'
	                           SELECT    @WHERESTING00  = '  AND   GOODSID IN ( select GOODSID from  GOODS  where Lcode like '+CHAR(39)+@LCODE+'%'+CHAR(39)+ ')'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  ='     '
			SELECT    @WHERESTING00  ='     '
 		END
		print @WHERESTING
		if     NOT (@modelNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   GOODSID IN ( select  GOODSID from Goods   where  modelNAME LIKE   '+CHAR(39)+'%'+@modelNAME+'%'+CHAR(39)+ '  )'
	                           SELECT    @WHERESTING00  = @WHERESTING00+'  AND   GOODSID IN ( select  GOODSID from Goods   where  modelNAME LIKE   '+CHAR(39)+'%'+@modelNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
			SELECT    @WHERESTING00= @WHERESTING00+'     '
 		END
		if     NOT (@GOODSCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   GOODSID IN ( select  GOODSID from Goods   where  CODE LIKE   '+CHAR(39)+'%'+@GOODSCODE+'%'+CHAR(39)+ '  )'
	                           SELECT    @WHERESTING00  = @WHERESTING00+'  AND   GOODSID IN ( select  GOODSID from Goods   where  CODE LIKE   '+CHAR(39)+'%'+@GOODSCODE+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  =@WHERESTING+'     '
			SELECT    @WHERESTING00  =@WHERESTING00+'     '
 		END

                        SELECT    @WHERESTING  = @WHERESTING+'  AND     BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+ @End_date+char(39) 

		if     NOT (@GOODSNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   GOODSID IN ( select  GOODSID from Goods   where  NAME LIKE   '+CHAR(39)+'%'+@GOODSNAME+'%'+CHAR(39)+ '  )'
	                           SELECT    @WHERESTING00  = @WHERESTING00+'  AND   GOODSID IN ( select  GOODSID from Goods   where  NAME LIKE   '+CHAR(39)+'%'+@GOODSNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
			SELECT    @WHERESTING00= @WHERESTING00+'     '
 		END
		if     NOT (@INF_COSTINGTYPEID=0)
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND  GOODSID IN ( select  GOODSID from Goods   where INF_COSTINGTYPEID =  '+str(@INF_COSTINGTYPEID)+ '  )'
	                           SELECT    @WHERESTING00  = @WHERESTING00+'  AND  GOODSID IN ( select  GOODSID from Goods   where INF_COSTINGTYPEID =  '+str(@INF_COSTINGTYPEID)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
			SELECT    @WHERESTING00  = @WHERESTING00+'     '
 		END
	declare @STOREHSFS   INTEGER

	       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )      
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                           SELECT    @STOREIDSTR   = '  AND   STOREID =  '+char(39)+@STOREID+char(39)
                            END
                            IF   @STOREHSFS=0
                            BEGIN
	                           SELECT    @STOREIDSTR   = '          '
                            END
     

Create Table #temptable10
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   GOODSID  nvarchar(50)  NULL,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
   UNIT  nvarchar(50)  NULL,             
	[INQTY] NUMERIC(20,10)  NULL ,
	[INPRICE] NUMERIC(20,10)  NULL ,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTQTY] NUMERIC(20,10)  NULL ,
	[OUTPRICE] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EQTY] NUMERIC(20,10)  NULL ,
	[EPRICE] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
	[MINQTY] NUMERIC(20,10)  NULL ,
	[MOUTQTY] NUMERIC(20,10)  NULL ,
	[MEQTY]NUMERIC(20,10)  NULL 
		)

Create Table #temptable1
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   GOODSID  nvarchar(50)  NULL,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
   UNIT  nvarchar(50)  NULL,             
	[INQTY] NUMERIC(20,10)  NULL ,
	[INPRICE] NUMERIC(20,10)  NULL ,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTQTY] NUMERIC(20,10)  NULL ,
	[OUTPRICE] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EQTY] NUMERIC(20,10)  NULL ,
	[EPRICE] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
	[MINQTY] NUMERIC(20,10)  NULL ,
	[MOUTQTY] NUMERIC(20,10)  NULL ,
	[MEQTY]NUMERIC(20,10)  NULL 
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   ID , BILLID,BILLTYPE,GOODSID,BILLCODE,BILLDATE,BILLTYPE,BILLTYPE, INQTY  ,INPRICE,INQTY*INPRICE, '
           SELECT  @SQLSTR = @SQLSTR+' OUTQTY  ,OUTPRICE,OUTQTY*OUTPRICE,EQTY,EPRICE,EAMOUNT,MINQTY,MOUTQTY,MEQTY '
           SELECT  @SQLSTR = @SQLSTR+'  from detailbillflow   where yyyymmbill=1   and (INOUTFLAG = 1  OR INOUTFLAG = 0)'  + @WHERESTING +@STOREIDSTR
           SELECT  @SQLSTR = @SQLSTR+'  order by goodsid,id '  
            EXEC( @SQLSTR)
		print @SQLSTR
           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   ID , BILLID,BILLTYPE,GOODSID,BILLCODE,BILLDATE,BILLTYPE,BILLTYPE, NULL AS INQTY  ,NULL AS INPRICE,NULL , '
           SELECT  @SQLSTR = @SQLSTR+' INQTY  ,INPRICE,INQTY*INPRICE,EQTY,EPRICE,EAMOUNT ,NULL AS MINQTY,MINQTY,MEQTY '
           SELECT  @SQLSTR = @SQLSTR+'  from detailbillflow   where yyyymmbill=1   and INOUTFLAG = -1'  + @WHERESTING +@STOREIDSTR
           SELECT  @SQLSTR = @SQLSTR+'  order by goodsid,id '  
            EXEC( @SQLSTR)



----------------------------------------
Create Table #GOODSTMP
      (   GOODSID  nvarchar(50)  NULL
		)

Create Table #temptable2
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   GOODSID  nvarchar(50)  NULL,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
   UNIT  nvarchar(50)  NULL,
   SPECNAME  nvarchar(50)  NULL,
   SPECNAMED  nvarchar(50)  NULL,
	[INQTY] NUMERIC(20,10)  NULL ,
	[INPRICE] NUMERIC(20,10)  NULL ,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTQTY] NUMERIC(20,10)  NULL ,
	[OUTPRICE] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EQTY] NUMERIC(20,10)  NULL ,
	[EPRICE] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
	[MINQTY] NUMERIC(20,10)  NULL ,
	[MOUTQTY] NUMERIC(20,10)  NULL ,
	[MEQTY]NUMERIC(20,10)  NULL 
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (Select  ID,BILLID,BILLTYPE,GOODSID , BILLCODE,BILLDATE,BILLTYPENAME,
                                                      isnull(INQTY,0) as INqty,isnull(INPRICE,0) as INPRICE , isnull(INAMOUNT,0) as INAMOUNT ,
                                                     isnull(OUTQTY,0) as OUTqty,isnull(OUTPRICE,0) as OUTPRICE , isnull(OUTAMOUNT,0) as OUTAMOUNT ,
                                                    isnull(EQTY,0) as EQTY , isnull(EPRICE,0) as EPRICE , isnull(EAMOUNT,0) as EAMOUNT
	                  from  #temptable1        )
                 begin
	    declare INOUTMXBREP Cursor for Select  ID,BILLID,BILLTYPE,GOODSID , BILLCODE,BILLDATE,BILLTYPENAME,
                                                      isnull(INQTY,0) as INqty,isnull(INPRICE,0) as INPRICE , isnull(INAMOUNT,0) as INAMOUNT ,
                                                     isnull(OUTQTY,0) as OUTqty,isnull(OUTPRICE,0) as OUTPRICE , isnull(OUTAMOUNT,0) as OUTAMOUNT ,
                                                    isnull(EQTY,0) as EQTY , isnull(EPRICE,0) as EPRICE , isnull(EAMOUNT,0) as EAMOUNT, isnull(MINQTY,0) as  MINQTY, isnull(MOUTQTY,0) as  MOUTQTY, isnull(MEQTY,0) as  MEQTY
	                  from  #temptable1         ORDER BY  GOODSID,BILLDATE,ID

	    Open INOUTMXBREP

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE,@GOODSID , @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INqty,@INPRICE,@INAMOUNT,@OUTqty,@OUTPRICE,@OUTAMOUNT,@EQTY,@EPRICE,@EAMOUNT,@MINQTY,@MOUTQTY,@MEQTY

                 SELECT  @GOODSID00=@GOODSID
                 SELECT  @GOODSCODE00=CODE,@GOODSNAME00=NAME,@UNIT= UNIT ,@SPECNAME=SPECNAME  FROM GOODS  WHERE GOODSID=@GOODSID
                 SELECT  @GOODSCODE00='货品编码：'+@GOODSCODE00
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID,GOODSID , BILLCODE,BILLTYPENAME ,SPECNAME  ,UNIT      )
                                           VALUES  (@COUNTID,@GOODSID00 , @GOODSCODE00,@GOODSNAME00,@SPECNAME,@UNIT)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
                           select @MAXBILLDATE=MAX(BILLDATE) FROM detailbillflow   WHERE  GOODSID=@GOODSID  AND   STOREID=@STOREID   AND     BILLDATE  < @begin_date   AND YYYYMMBILL=1

			print @MAXBILLDATE

			if    @MAXBILLDATE is null
			begin
			SET  @BQTY=0
			SET  @MBQTY=0
			print '1111'
			SET  @BPRICE=0
			SET  @BAMOUNT=0
			end
			else
			begin
		                           SELECT  @MAXID=MAX(ID)  FROM detailbillflow  WHERE  GOODSID=@GOODSID  AND   STOREID=@STOREID   AND  BILLDATE=@MAXBILLDATE    AND YYYYMMBILL=1   ----  BILLDATE  < @begin_date
             		                            IF @MAXID IS NULL
 				BEGIN
				SET  @BQTY=0
				SET  @MBQTY=0
				SET  @BPRICE=0
				SET  @BAMOUNT=0
				END
                                        	ELSE
				BEGIN
		                           SELECT @BQTY=EQTY,@MBQTY=MEQTY,@BPRICE=EPRICE,@BAMOUNT=EAMOUNT   FROM   detailbillflow  WHERE ID=@MAXID
				END
			end
                            END
                            IF   @STOREHSFS=0
                            BEGIN
                           select @MAXBILLDATE=MAX(BILLDATE) FROM detailbillflow   WHERE  GOODSID=@GOODSID   AND     BILLDATE  < @begin_date  AND YYYYMMBILL=1
                           SELECT  @MAXID=MAX(ID)  FROM detailbillflow  WHERE  GOODSID=@GOODSID     AND  BILLDATE=@MAXBILLDATE  AND YYYYMMBILL=1  ----  BILLDATE  < @begin_date
                                         IF @MAXID IS NULL
 			BEGIN
			SET  @BQTY=0
			SET  @BPRICE=0
			SET  @MBQTY=0
			SET  @BAMOUNT=0
			END
                                        ELSE
			BEGIN
	                           SELECT @BQTY=EQTY,@MBQTY=MEQTY,@BPRICE=EPRICE,@BAMOUNT=EAMOUNT   FROM   detailbillflow  WHERE ID=@MAXID
			END
                            END
                                                              
                          INSERT    INTO   #temptable2  (ID,GOODSID , BILLTYPENAME,
                                                               EQTY,EPRICE,EAMOUNT,MEQTY)
                                           VALUES  (@COUNTID,@GOODSID00 , '期初结存',
                                                               @BQTY,@BPRICE,@BAMOUNT,@MBQTY)
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
                       SELECT  @BILLTYPENAME=NAME FROM  BILLNAME  WHERE @BILLTYPENAME=BILLTYPEID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
                      IF  @GOODSID00=@GOODSID
		BEGIN
                          INSERT    INTO   #temptable2  (ID,BILLID,BILLTYPE,GOODSID , BILLCODE,BILLDATE,BILLTYPENAME,UNIT,
                                                               INqty,INPRICE,INAMOUNT,OUTqty,OUTPRICE,OUTAMOUNT,EQTY,EPRICE,EAMOUNT,MINQTY,MOUTQTY,MEQTY)
                                           VALUES  (@COUNTID,@BILLID,@BILLTYPE,@GOODSID , @BILLCODE,@BILLDATE,@BILLTYPENAME,@UNIT,
                                                               @INqty,@INPRICE,@INAMOUNT,@OUTqty,@OUTPRICE,@OUTAMOUNT,@EQTY,@EPRICE,@EAMOUNT,@MINQTY,@MOUTQTY,@MEQTY)
                          END
                     ELSE
                          BEGIN

                          INSERT    INTO   #temptable2  (ID,GOODSID , BILLTYPENAME,
                                                               EQTY,EPRICE,EAMOUNT,MEQTY)
                                           VALUES  (@COUNTID,@GOODSID00 , '期末结存',
                                                              @EQTYPREV,@EPRICEPREV,@EAMOUNTPREV,@MEQTYPREV)
---------------------------------------------------------------
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID,GOODSID   )                  ----------插入空行
                                           VALUES  (@COUNTID,@GOODSID00 )
-------------------------------------------------------------------------------------------------------------------------------------------------------------
	                 SELECT @GOODSID00=@GOODSID
------------------------------------------------------
                 SELECT  @GOODSCODE00='货品编码：'+CODE,@GOODSNAME00=NAME,@UNIT= UNIT,@SPECNAME=SPECNAME   FROM GOODS  WHERE GOODSID=@GOODSID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID,GOODSID , BILLCODE,BILLTYPENAME ,SPECNAME,UNIT        )
                                           VALUES  (@COUNTID,@GOODSID00 , @GOODSCODE00,@GOODSNAME00,@SPECNAME,@UNIT)

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
                           select @MAXBILLDATE=MAX(BILLDATE) FROM detailbillflow   WHERE  GOODSID=@GOODSID  AND   STOREID=@STOREID   AND     BILLDATE  < @begin_date   AND YYYYMMBILL=1
		                           SELECT  @MAXID=MAX(ID)  FROM detailbillflow  WHERE  GOODSID=@GOODSID  AND   STOREID=@STOREID   AND  BILLDATE=@MAXBILLDATE    AND YYYYMMBILL=1   ----  BILLDATE  < @begin_date
             		                            IF @MAXID IS NULL
 				BEGIN
				SET  @BQTY=0
				SET  @MBQTY=0
				SET  @BPRICE=0
				SET  @BAMOUNT=0
				END
                                        	ELSE
				BEGIN
		                           SELECT @BQTY=EQTY,@MBQTY=MEQTY,@BPRICE=EPRICE,@BAMOUNT=EAMOUNT   FROM   detailbillflow  WHERE ID=@MAXID
				END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
                           select @MAXBILLDATE=MAX(BILLDATE) FROM detailbillflow   WHERE  GOODSID=@GOODSID   AND     BILLDATE  < @begin_date  AND YYYYMMBILL=1
                           SELECT  @MAXID=MAX(ID)  FROM detailbillflow  WHERE  GOODSID=@GOODSID     AND  BILLDATE=@MAXBILLDATE  AND YYYYMMBILL=1  ----  BILLDATE  < @begin_date
                                         IF @MAXID IS NULL
 			BEGIN
			SET  @BQTY=0
			SET  @MBQTY=0
			SET  @BPRICE=0
			SET  @BAMOUNT=0
			END
                                        ELSE
			BEGIN
	                           SELECT @BQTY=EQTY, @MBQTY=MEQTY,@BPRICE=EPRICE,@BAMOUNT=EAMOUNT   FROM   detailbillflow  WHERE ID=@MAXID
			END
                            END
                                                              
                          INSERT    INTO   #temptable2  (ID,GOODSID , BILLTYPENAME,
                                                               EQTY,EPRICE,EAMOUNT,MEQTY)
                                           VALUES  (@COUNTID,@GOODSID00 , '期初结存',
                                                               @BQTY,@BPRICE,@BAMOUNT,@MBQTY)

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
                          INSERT    INTO   #temptable2  (ID,BILLID,BILLTYPE,GOODSID , BILLCODE,BILLDATE,BILLTYPENAME,UNIT,
                                                               INqty,INPRICE,INAMOUNT,OUTqty,OUTPRICE,OUTAMOUNT,EQTY,EPRICE,EAMOUNT,MINQTY,MOUTQTY,MEQTY)
                                           VALUES  (@COUNTID,@BILLID,@BILLTYPE,@GOODSID , @BILLCODE,@BILLDATE,@BILLTYPENAME,@UNIT,
                                                               @INqty,@INPRICE,@INAMOUNT,@OUTqty,@OUTPRICE,@OUTAMOUNT,@EQTY,@EPRICE,@EAMOUNT,@MINQTY,@MOUTQTY,@MEQTY)
-------------------------------------------------

-----------------------------------------------------------------------
                          END
                       SET @EQTYPREV=@EQTY
                       SET @MEQTYPREV=@MEQTY
		SET    @EPRICEPREV=@EPRICE
 		    SET @EAMOUNTPREV=@EAMOUNT

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE,@GOODSID , @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INqty,@INPRICE,@INAMOUNT,@OUTqty,@OUTPRICE,@OUTAMOUNT,@EQTY,@EPRICE,@EAMOUNT,@MINQTY,@MOUTQTY,@MEQTY

	    END           ------- INOUTMXBREP  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID,GOODSID , BILLTYPENAME,
                                                               EQTY,EPRICE,EAMOUNT,MEQTY)
                                           VALUES  (@COUNTID,@GOODSID00 , '期末结存',
                                                              @EQTY,@EPRICE,@EAMOUNT,@MEQTY)

	    close INOUTMXBREP
	    deallocate INOUTMXBREP
        end     ------------  if exists
---------------------------
---------解决当前仓库本期间未发生业务的货品
--                  delete    #temptable1
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN       

		           SELECT  @SQLSTR = ' INSERT #GOODSTMP  '
		           SELECT  @SQLSTR = @SQLSTR+' SELECT DISTINCT GOODSID  FROM   detailbillflow  WHERE   (GOODSID  NOT IN (SELECT GOODSID  FROM   #temptable1 )  )  AND ( GOODSID  IN   (SELECT GOODSID  FROM detailbillflow  WHERE  EQTY <>0   ))  '+@WHERESTING00+ @STOREIDSTR
		            EXEC( @SQLSTR)
                                          
		    declare INOUTMXB Cursor for SELECT GOODSID  FROM   #GOODSTMP
		    Open INOUTMXB

		    fetch INOUTMXB into   @GOODSID

		    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
		    begin
					----------------应该取得月结记录
		                           select @MAXBILLDATE=MAX(BILLDATE) FROM detailbillflow   WHERE  GOODSID=@GOODSID  AND   STOREID=@STOREID   AND     BILLDATE  < =@begin_date   AND YYYYMMBILL=1

		                           SELECT  @ID=MAX(ID)  FROM detailbillflow  WHERE  GOODSID=@GOODSID  AND   STOREID=@STOREID      AND YYYYMMBILL=1  and  BILLDATE  = @MAXBILLDATE

             		                 INSERT  #temptable10  
	             		   SELECT      ID,NULL AS BILLID,NULL AS BILLTYPE, GOODSID,BILLCODE,BILLDATE,BILLTYPE,BILLTYPE, NULL AS INQTY  ,NULL AS INPRICE,NULL ,  
				 INQTY  ,INPRICE,INQTY*INPRICE, EQTY, EPRICE,  EAMOUNT,MINQTY,MOUTQTY,MEQTY
                          		      FROM   detailbillflow  WHERE    ID = @ID   
			    fetch INOUTMXB into   @GOODSID
             		     END
		    close INOUTMXB
		    deallocate INOUTMXB
                           END          ---------                      IF   @STOREHSFS=1    ---分仓库核算

                            IF   @STOREHSFS=0
                            BEGIN

		           SELECT  @SQLSTR = ' INSERT #GOODSTMP  '
		           SELECT  @SQLSTR = @SQLSTR+' SELECT DISTINCT GOODSID  FROM   detailbillflow  WHERE   (GOODSID  NOT IN (SELECT GOODSID  FROM   #temptable1 )  )  AND ( GOODSID  IN   (SELECT GOODSID  FROM detailbillflow  WHERE  EQTY <>0 ))  '+@WHERESTING00+ @STOREIDSTR
		            EXEC( @SQLSTR)
                                          
		    declare INOUTMXB Cursor for SELECT GOODSID  FROM   #GOODSTMP
		    Open INOUTMXB

		    fetch INOUTMXB into   @GOODSID

		    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
		    begin

		                           select @MAXBILLDATE=MAX(BILLDATE) FROM detailbillflow   WHERE  GOODSID=@GOODSID     AND     BILLDATE  < =@begin_date   AND YYYYMMBILL=1
		                           SELECT  @ID=MAX(ID)  FROM detailbillflow  WHERE  GOODSID=@GOODSID    AND YYYYMMBILL=1  and  BILLDATE  = @MAXBILLDATE
             		                 INSERT  #temptable10  
	             		   SELECT      ID,NULL AS BILLID,NULL AS BILLTYPE, GOODSID,BILLCODE,BILLDATE,BILLTYPE,BILLTYPE, NULL AS INQTY  ,NULL AS INPRICE,NULL ,  
				 INQTY  ,INPRICE,INQTY*INPRICE,EQTY,EPRICE,EAMOUNT,MINQTY,MOUTQTY,MEQTY
                          		      FROM   detailbillflow  WHERE    ID = @ID
			    fetch INOUTMXB into   @GOODSID
             		     END
		    close INOUTMXB
		    deallocate INOUTMXB
                            END
---------------------------------------------
	    declare INOUTMXBREP Cursor for Select  ID,BILLID,BILLTYPE,GOODSID , BILLCODE,BILLDATE,BILLTYPENAME,
                                                      isnull(INQTY,0) as INqty,isnull(INPRICE,0) as INPRICE , isnull(INAMOUNT,0) as INAMOUNT ,
                                                     isnull(OUTQTY,0) as OUTqty,isnull(OUTPRICE,0) as OUTPRICE , isnull(OUTAMOUNT,0) as OUTAMOUNT ,
                                                    isnull(EQTY,0) as EQTY , isnull(EPRICE,0) as EPRICE , isnull(EAMOUNT,0) as EAMOUNT, isnull(MINQTY,0) as  MINQTY, isnull(MOUTQTY,0) as  MOUTQTY, isnull(MEQTY,0) as  MEQTY
	                  from  #temptable10         ORDER BY  GOODSID,BILLDATE,ID

	    Open INOUTMXBREP

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE,@GOODSID , @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INqty,@INPRICE,@INAMOUNT,@OUTqty,@OUTPRICE,@OUTAMOUNT,@EQTY,@EPRICE,@EAMOUNT,@MINQTY,@MOUTQTY,@MEQTY

	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
                 SELECT  @GOODSID00=@GOODSID
                 SELECT  @GOODSCODE00=CODE,@GOODSNAME00=NAME,@UNIT= UNIT,@SPECNAME=SPECNAME   FROM GOODS  WHERE GOODSID=@GOODSID
                 SELECT  @GOODSCODE00='货品编码：'+@GOODSCODE00
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID,GOODSID , BILLCODE,BILLTYPENAME ,SPECNAME  ,UNIT      )
                                           VALUES  (@COUNTID,@GOODSID00 , @GOODSCODE00,@GOODSNAME00,@SPECNAME,@UNIT)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                                                              
                          INSERT    INTO   #temptable2  (ID,GOODSID , BILLTYPENAME,
                                                               EQTY,EPRICE,EAMOUNT,MEQTY)
                                           VALUES  (@COUNTID,@GOODSID00 , '期初结存',
                                                               @EQTY,@EPRICE,@EAMOUNT,@MEQTY)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
                          INSERT    INTO   #temptable2  (ID,GOODSID , BILLTYPENAME,
                                                               EQTY,EPRICE,EAMOUNT,MEQTY)
                                           VALUES  (@COUNTID,@GOODSID00 , '期末结存',
                                                              @EQTY,@EPRICE,@EAMOUNT,@MEQTY)

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID,GOODSID   )                  ----------插入空行
                                           VALUES  (@COUNTID,@GOODSID00 )
-------------------------------------------------------------------------------------------------------------------------------------------------------------

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE,@GOODSID , @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INqty,@INPRICE,@INAMOUNT,@OUTqty,@OUTPRICE,@OUTAMOUNT,@EQTY,@EPRICE,@EAMOUNT,@MINQTY,@MOUTQTY,@MEQTY


	    END           ------- INOUTMXBREP  WHILE

	    close INOUTMXBREP
	    deallocate INOUTMXBREP
---------------------------


--update a set a.字段=” from A a inner join B b on a.PId=b.FId where 条件
update #temptable2 set #temptable2.SPECNAMED=b.SPECNAMED from #temptable2 inner join VIEWXSCKGOODSCODE b on #temptable2.BILLID=b.BILLID and #temptable2.BILLtype=b.billtype

 SELECT ID, BILLID, BILLTYPE,    #temptable2.GOODSID ,   BILLCODE  ,   BILLDATE  ,   BILLTYPENAME ,  #temptable2.UNIT,#temptable2.SPECNAME,  #temptable2.SPECNAMED  ,INQTY,INPRICE,INAMOUNT,OUTQTY,OUTPRICE,	OUTAMOUNT,EQTY,EPRICE,EAMOUNT,#temptable2.MINQTY   AS MINQTY,#temptable2.MOUTQTY  as MOUTQTY ,#temptable2.MEQTY AS MEQTY
                           FROM #temptable2   ,GOODS   WHERE  #temptable2.GOODSID=GOODS.GOODSID    ORDER BY GOODS.CODE ,ID









----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG























--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[STORELEDGER](@STOREID varchar(8) ,                        -----如果为0000则全部仓库
                                                                                           @YYYYMM  varchar(8),      --------为当前会计期间
						           @LCODE  varchar(10),             ---如果LCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSCODE  varchar(20),             ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSNAME  varchar(20),             ---如果GOODSNAME  为‘GGGG’表示不对类别进行查询
                                                           @INF_COSTINGTYPEID   smallint    ,  --------同价调拨标志   0  代表 不作为过滤条件
						           @modelNAME  varchar(20),             ---如果modelNAME  为‘GGGG’表示不对类别进行查询
                                                           @ZEROFLAG   smallint ,     --------同价调拨标志   0  代表 不作为过滤条件
						           @SPECNAME  varchar(20),             ---如果modelNAME  为‘GGGG’表示不对类别进行查询
						           @MAKEAREA  varchar(20) ,             ---如果modelNAME  为‘GGGG’表示不对类别进行查询
                                                           @StoreIDFlag   smallint     --------同价调拨标志   0  代表 不作为过滤条件


                         
                                                      )   --APSOFTENCRYPTION       WITH ENCRYPTION
as



Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @WHERESTING   varchar(1800),
        @STOREIDSTR   varchar(100),
        @DBSTING   varchar(100)
                   set @now_date=(select   max(billDATE)   FROM DETAILBILLFLOW)

--@WHERESTR='  and 1=1 '
		if     NOT (@LCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = '  AND   I.GOODSID IN ( select GOODSID from  GOODS  where Lcode like '+CHAR(39)+@LCODE+'%'+CHAR(39)+ ')'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  ='     '
 		END
		if     NOT (@GOODSCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  CODE LIKE   '+CHAR(39)+'%'+@GOODSCODE+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  =@WHERESTING+'     '
 		END
		if     NOT (@modelNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  modelNAME LIKE   '+CHAR(39)+'%'+@modelNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END

		if     NOT (@SpecName='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  SpecName LIKE   '+CHAR(39)+'%'+@SpecName+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END
		if     NOT (@MAKEAREA='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  MAKEAREA LIKE   '+CHAR(39)+'%'+@MAKEAREA+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END

		if     NOT (@GOODSNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  NAME LIKE   '+CHAR(39)+'%'+@GOODSNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END
		if     NOT (@INF_COSTINGTYPEID=0)
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where INF_COSTINGTYPEID =  '+str(@INF_COSTINGTYPEID)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END
		if     NOT (@STOREID='0000')
                BEGIN
	                           SELECT    @STOREIDSTR   = '  AND   STOREID =  '+CHAR(39)+@STOREID+CHAR(39)
                END
                ELSE
                BEGIN
			IF @StoreIDFlag=1 
        		BEGIN
		        	SELECT    @STOREIDSTR   = '  AND   STOREID NOT IN (select STOREID from Store where liuHFlag=1 or YuShouFlag=1) '
		        END
                	ELSE
	                BEGIN
			
				SELECT    @STOREIDSTR   = '     '
	 		END
 		END

------@StoreIDFlag=1  剔除留货仓库与预售仓库 

                       print   @WHERESTING


----------------------------------------------------
		---计算在途量

		delete  Store_GoodsID_ZaiTu

		INSERT INTO  Store_GoodsID_ZaiTu	select GoodsID ,StoreID,
			Sum(QuanTity)  as QuanTity ,Sum(unitqty) as Unitqty  from  VIEWGOODS_ZaiTu
			  group by GOODSID,StoreID
			  order by GoodsID,StoreID

----------------------------------------------------


Create Table #temptable10
      (GOODSID  varchar(10) primary key,
	  EQTY NUMERIC(20,10)  NULL, 
	  UNITQTY NUMERIC(20,10)  NULL, 
	  ZaiTuQuanTity NUMERIC(20,10)  NULL, 
	  ZaiTuUNITQTY NUMERIC(20,10)  NULL 
		)

----------------------------------------------------
		SELECT @SQLSTR='	 select  I.GOODSID,       '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)+ isnull(E.INQTY,0)  as EQTY, '   --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0)  as UNITQTY, '   --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(BXX.QuanTity,0) as ZaiTuQuanTity, isnull(BXX.UNITQTY,0)  as ZaiTuUNITQTY '   --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from Goods  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(INQTY*INOUTFLAG)  as INQTY  ,sum(MINQTY*INOUTFLAG)  as MINQTY '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)  +@STOREIDSTR                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(BQTY) as BQTY ,sum(MBQTY) as MBQTY '
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) +@STOREIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID  '
------------------------以上部分是取当前库存
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(QuanTity) as QuanTity ,sum(unitqty) as UNITQTY '
		SELECT @SQLSTR=@SQLSTR+' from Store_GoodsID_ZaiTu '
		SELECT @SQLSTR=@SQLSTR+' where 1=1  ' +@STOREIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as BXX on BXX.GOODSID = I.GOODSID  '

                SELECT @SQLSTR=@SQLSTR+'  where     I. GOODSID in (select GOODSID from DETAILBILLFLOW where YYYYMM >='+char(39)+@YYYYMM+char(39)+@STOREIDSTR+')'  + @WHERESTING 
		SELECT @SQLSTR=@SQLSTR+'          order by  I.CODE                '

		INSERT INTO  #temptable10  EXEC(@SQLSTR)


		IF  @ZEROFLAG=0
		BEGIN
			SELECT #temptable10.*,Goods.DSPRICE,Goods.MQTYSPRICE,Goods.DSPRICETax  FROM  #temptable10,Goods  WHERE #temptable10.GOODSID=GOODS.GOODSID AND #temptable10.UNITQTY <>0  ORDER BY GOODS.CODE
		END
		IF  @ZEROFLAG=1 
		BEGIN
			SELECT #temptable10.*,Goods.DSPRICE,Goods.MQTYSPRICE,Goods.DSPRICETax  FROM  #temptable10,Goods  WHERE #temptable10.GOODSID=GOODS.GOODSID   ORDER BY GOODS.CODE
		END




















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG
















--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------

CREATE PROCEDURE STORELEDGER_BJ(           @YYYYMM  varchar(8),     --------为当前会计期间
                         @Flag int
                                                      )    --APSOFTENCRYPTION       WITH ENCRYPTION
as



Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000)
---------------------------------------------------
Declare @KuCunBJType  varchar(10)

       SELECT    @KuCunBJType=(SELECT  KuCunBJType  FROM   ACCINFO    WHERE   GUID='0001' )           


CREATE TABLE #GOODSTMP (
	[GOODSID] [varchar] (25) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[TOPQTY] NUMERIC(20,10) NULL ,
	[DOWNQTY] NUMERIC(20,10) NULL ,
	[MEQTY] NUMERIC(20,10) NULL, 
	[EQTY] NUMERIC(20,10) NULL 
) ON [PRIMARY]

		SELECT @SQLSTR='	 select  I.GOODSID,   isnull(I.TOPQTY,0)    AS TOPQTY,isnull(I.DOWNQTY,0)    AS DOWNQTY,     '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0)  as MEQTY ,'   --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)+ isnull(E.INQTY,0)  as EQTY  '   --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from Goods  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(INQTY*INOUTFLAG)  as INQTY,sum(MINQTY*INOUTFLAG)  as MINQTY   '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)               --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(BQTY) as BQTY ,sum(MBQTY) as MBQTY'
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39)
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where     I. GOODSID in (select GOODSID from DETAILBILLFLOW where YYYYMM >='+char(39)+@YYYYMM+char(39)+')'  
--		SELECT @SQLSTR=@SQLSTR+'          order by  I.GOODSID                '
		SELECT @SQLSTR=@SQLSTR+'          order by  I.CODE                '
------------------------------------------------------------------------
	INSERT INTO   #GOODSTMP    EXEC(@SQLSTR)
	     IF @KuCunBJType = '数量' 
	     begin
		  IF @Flag=1	
		   begin
                   SELECT *  FROM #GOODSTMP   WHERE  MEQTY<DOWNQTY    AND (TOPQTY<>DOWNQTY )
		   end
		  IF @Flag=2	
		   begin
                   SELECT *  FROM #GOODSTMP   WHERE  MEQTY>TOPQTY    AND (TOPQTY<>DOWNQTY )
		   end
		  IF @Flag=3	
		   begin
                   SELECT *  FROM #GOODSTMP   WHERE  ( (MEQTY>TOPQTY)   OR  (MEQTY<DOWNQTY)   )  AND (TOPQTY<>DOWNQTY )
		   end
	     end
	     IF @KuCunBJType = '重量' 
	     begin
		  IF @Flag=1	
		   begin
                   SELECT *  FROM #GOODSTMP   WHERE  EQTY<DOWNQTY    AND (TOPQTY<>DOWNQTY )
		   end
		  IF @Flag=2	
		   begin
                   SELECT *  FROM #GOODSTMP   WHERE  EQTY>TOPQTY    AND (TOPQTY<>DOWNQTY )
		   end
		  IF @Flag=3	
		   begin
                   SELECT *  FROM #GOODSTMP   WHERE  ( (EQTY>TOPQTY)   OR  (EQTY<DOWNQTY)   )  AND (TOPQTY<>DOWNQTY )
		   end
	     end
	 
	
  		











----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG


















--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------

CREATE PROCEDURE STORELEDGER_BJ_Creat_CGDD(           @YYYYMM  varchar(8),     --------为当前会计期间
						      @sysdate   varchar(10),  
						      @MAKEMAN   varchar(10), 
                                                      @RETURNSTRING            varchar(60)    output       ---单据编号   
 
                                                      )    --APSOFTENCRYPTION       WITH ENCRYPTION
as



Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000)
---------------------------------------------------
Declare @KuCunBJType  varchar(10)
declare @ID   varchar(15)           
declare @BILLID00    varchar(15)           
declare @STOREID    varchar(15)           
declare @YYYYMM00    varchar(6)           
declare @BILLTYPE00    [int]     
declare @COUNT_MY    [int]     
declare @MAKEMAN00   [varchar] (50)   
declare @CODE00   [varchar] (25)   
declare 	@ITEMNO00    varchar (30) 
declare 	@TOPQTY NUMERIC(20,6)
declare 	@DOWNQTY NUMERIC(20,6) 
declare 	@UNITQTY NUMERIC(20,6)
declare 	@QUANTITY NUMERIC(20,6) 
declare 	@Rate NUMERIC(20,10) 
declare @GOODSID00    varchar(15)           


       SELECT    @KuCunBJType=(SELECT  KuCunBJType  FROM   ACCINFO    WHERE   GUID='0001' )           


CREATE TABLE #GOODSTMP (
	[GOODSID] [varchar] (25) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[TOPQTY] NUMERIC(20,10) NULL ,
	[DOWNQTY] NUMERIC(20,10) NULL ,
	[MEQTY] NUMERIC(20,10) NULL, 
	[EQTY] NUMERIC(20,10) NULL 
) ON [PRIMARY]

		SELECT @SQLSTR='	 select  I.GOODSID,   isnull(I.TOPQTY,0)    AS TOPQTY,isnull(I.DOWNQTY,0)    AS DOWNQTY,     '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0)  as MEQTY ,'   --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)+ isnull(E.INQTY,0)  as EQTY  '   --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from Goods  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(INQTY*INOUTFLAG)  as INQTY,sum(MINQTY*INOUTFLAG)  as MINQTY   '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)               --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(BQTY) as BQTY ,sum(MBQTY) as MBQTY'
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39)
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where     I. GOODSID in (select GOODSID from DETAILBILLFLOW where YYYYMM >='+char(39)+@YYYYMM+char(39)+')'  
--		SELECT @SQLSTR=@SQLSTR+'          order by  I.GOODSID                '
		SELECT @SQLSTR=@SQLSTR+'          order by  I.CODE                '
------------------------------------------------------------------------
	INSERT INTO   #GOODSTMP    EXEC(@SQLSTR)
	 

	     IF @KuCunBJType = '数量' 
	     begin
                 set  @COUNT_MY=( Select  Count(*)   FROM #GOODSTMP   WHERE  MEQTY<DOWNQTY    AND (TOPQTY<>DOWNQTY ))
	     end
	     IF @KuCunBJType = '重量' 
	     begin
                 set  @COUNT_MY=( Select  Count(*)    FROM #GOODSTMP   WHERE  EQTY<DOWNQTY    AND (TOPQTY<>DOWNQTY ))
	     end
		if @COUNT_MY=0 
		begin

		   set @RETURNSTRING='没有库存低的钢材，不能生成采购订单'
                       RETURN
		end
----------------------------------------------------------------------------------------------------------以下是插入主表
	
             		    execute  GET_BILL_NO     'STORECGDDM',@sysdate,'CD',@bill_no_selfd = @CODE00 output
             		    execute  GETKEYVALUE     'STORECGDDM',@R_KeyValue = @BILLID00 output

                           INSERT  INTO STORECGDDM   (BILLID,YYYYMM,CODE,MAKEMAN,BILLDATE,BILLTYPE)
                                      VALUES (@BILLID00,@YYYYMM,@CODE00,@MAKEMAN,@SYSDATE,103)
  		
----------------------------------------------------------------------以下是插入从表
----------------------------------------------------------------------以下是插入从表
	     IF @KuCunBJType = '数量' 
	     begin
                  declare SM_Consign_DATANEXT Cursor for Select   GOODSID,TOPQTY,DOWNQTY   FROM #GOODSTMP   WHERE  MEQTY<DOWNQTY    AND (TOPQTY<>DOWNQTY )
	     end
	     IF @KuCunBJType = '重量' 
	     begin
                  declare SM_Consign_DATANEXT Cursor for Select   GOODSID,TOPQTY,DOWNQTY    FROM #GOODSTMP   WHERE  EQTY<DOWNQTY    AND (TOPQTY<>DOWNQTY )
	     end


    Open SM_Consign_DATANEXT

    fetch SM_Consign_DATANEXT into @GOODSID00,@TOPQTY,@DOWNQTY

    while @@fetch_status = 0            ----开始
    begin
             		    execute  GETKEYVALUE     'STORECGDDD',@R_KeyValue = @ITEMNO00 output
	select @StoreID=(Select Storeid from goods where goodsid=@GOODSID00)

	Select Storeid from goods where storeid is null  OR len(storeid)<1

	 IF  @StoreID is null  OR len(@storeid)<1
	 begin
          select @StoreID=(Select top 1 Storeid from Store)
	 end	

        set @RATE =   (select ISNULL(RATE,0)  from GOODS where  GOODSID = @GOODSID00)


---------------根据理算系数核算重量与数量


	     IF @KuCunBJType = '数量' 
	     begin
		select @UNITQTY=(@TOPQTY+@DOWNQTY)/2
			IF @RATE<>0
			Begin
	   		 SELECT @QUANTITY=@RATE*@UNITQTY
			END	

	     end
	     IF @KuCunBJType = '重量' 
	     begin
		select @QUANTITY=(@TOPQTY+@DOWNQTY)/2
			IF @RATE<>0
			Begin
			   	 SELECT @UNITQTY=@QUANTITY/@RATE
			END	
	     end


		    insert into STORECGDDD 
		    (BILLID, ITEMNO,UNITQTY,STOREID,GOODSID,QUANTITY)
		    Values
		    (@BILLID00,@ITEMNO00 ,@UNITQTY,@STOREID,@GOODSID00 ,@QUANTITY)    

    fetch SM_Consign_DATANEXT into @GOODSID00,@TOPQTY,@DOWNQTY

    END           ------- SM_Consign_DATANEXT  WHILE

    close SM_Consign_DATANEXT
    deallocate SM_Consign_DATANEXT


   set @RETURNSTRING='成功生成采购订单，单号为'+@CODE00










----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













--------------------------------------------------------------------
--------------------------------------------------------------------2005.08.16
--------------------------------------------------------------------2005.09.02


CREATE PROCEDURE STORELEDGER_CRAET_PD(@STOREID varchar(8) ,                        -----如果为0000则全部仓库
                                                                                           @YYYYMM  varchar(8),      --------为当前会计期间
						           @sysdate   varchar(10),  
						           @MAKEMAN   varchar(10),  
						           @LCODE  varchar(10),             ---如果LCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSCODE  varchar(20),             ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSNAME  varchar(20),             ---如果GOODSNAME  为‘GGGG’表示不对类别进行查询
                                                                                           @INF_COSTINGTYPEID   smallint      --------同价调拨标志   0  代表 不作为过滤条件

                         
                                                      )    --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @WHERESTING   varchar(1800),
        @STOREIDSTR   varchar(100),
        @DBSTING   varchar(100)


declare @ID   varchar(15)           
declare @BILLID00    varchar(15)           
declare @YYYYMM00    varchar(6)           
declare @BILLTYPE00    [int]     
declare @MAKEMAN00   [varchar] (50)   
declare @CODE00   [varchar] (25)   
declare 	@ITEMNO00    varchar (30) 
declare @STOREID00    varchar(15)           
declare @VENDORID    varchar(15)           
declare @GOODSID00    varchar(15)           
declare	@APRICE00  NUMERIC(20,10) 
declare	@MEQTY  NUMERIC(20,10) 
declare	@QUANTITY00 NUMERIC(20,10)       --存放实际数量
declare	@PRICE00 NUMERIC(20,10)      ------存放帐面数量



                   set @now_date=(select   max(billDATE)   FROM DETAILBILLFLOW)

--@WHERESTR='  and 1=1 '
		if     NOT (@LCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = '  AND   I.GOODSID IN ( select GOODSID from  GOODS  where Lcode like '+CHAR(39)+@LCODE+'%'+CHAR(39)+ ')'

                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  ='     '
 		END
		if     NOT (@GOODSCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  CODE LIKE   '+CHAR(39)+'%'+@GOODSCODE+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  =@WHERESTING+'     '
 		END
		if     NOT (@GOODSNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  NAME LIKE   '+CHAR(39)+'%'+@GOODSNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END
		if     NOT (@INF_COSTINGTYPEID=0)
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where INF_COSTINGTYPEID =  '+str(@INF_COSTINGTYPEID)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'   '
 		END
                          SELECT    @STOREIDSTR   = '  AND  STOREID =  '+@STOREID

----------------------------------------------------

CREATE TABLE #LEDGER (
	[ID] [varchar] (25) COLLATE Chinese_PRC_CI_AS NULL ,
	[GOODSID] [varchar] (25) COLLATE Chinese_PRC_CI_AS NULL ,
	[STOREID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
	[INF_COSTINGTYPEID] [int] NULL ,
	[EQTY] NUMERIC(20,10) NULL, 
	[MEQTY] NUMERIC(20,10) NULL 
) ON [PRIMARY]

----------------------------------------------------
		SELECT @SQLSTR='	 select      NULL AS ID , I.GOODSID,   '+@STOREID+'    AS   STOREID, I.INF_COSTINGTYPEID ,    '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)+ isnull(E.INQTY,0)  as EQTY, '   --期末数量
		SELECT @SQLSTR=@SQLSTR+' ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0)  as MEQTY '   --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from Goods  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(INQTY*INOUTFLAG)  as INQTY,sum(MINQTY*INOUTFLAG)  as MINQTY  '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)  +@STOREIDSTR                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(BQTY) as BQTY , sum(MBQTY) as MBQTY '
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) +@STOREIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where  (  INF_COSTINGTYPEID  in (1,3,6) )   and   I. GOODSID in (select GOODSID from DETAILBILLFLOW where YYYYMM >='+char(39)+@YYYYMM+char(39)+@STOREIDSTR+')'  + @WHERESTING 
		SELECT @SQLSTR=@SQLSTR+'          order by  I.CODE                '
------------------------------------------------------------------------

		INSERT INTO   #LEDGER    EXEC(@SQLSTR)

                            DELETE    #LEDGER   WHERE EQTY=0

----------------------------------------------------------------------------------------------------------以下是插入主表
             		    execute  GET_BILL_NO     'STORECKPDM',@sysdate,'PD',@bill_no_selfd = @CODE00 output
             		    execute  GETKEYVALUE     'STORECKPDM',@R_KeyValue = @BILLID00 output

                           INSERT  INTO STORECKPDM   (BILLID,YYYYMM,CODE,MAKEMAN,BILLDATE,BILLTYPE)
                                      VALUES (@BILLID00,@YYYYMM,@CODE00,@MAKEMAN,@SYSDATE,6)
----------------------------------------------------------------------以下是插入从表
    declare SM_Consign_DATANEXT Cursor for Select   ID,GOODSID,EQTY,MEQTY   from #LEDGER

    Open SM_Consign_DATANEXT

    fetch SM_Consign_DATANEXT into @ID,@GOODSID00,@PRICE00,@MEQTY  

    while @@fetch_status = 0            ----开始
    begin
             		    execute  GETKEYVALUE     'STORECKPD',@R_KeyValue = @ITEMNO00 output
		    insert into STORECKPDD 
		    (BILLID, ITEMNO,PRICE,STOREID,GOODSID,REDETAILBILLFLOWID,UNITPRICE)
		    Values
		    (@BILLID00,@ITEMNO00 ,@PRICE00,@STOREID,@GOODSID00 ,@ID,@MEQTY)    

    fetch SM_Consign_DATANEXT into @ID,@GOODSID00,@PRICE00,@MEQTY  

    END           ------- SM_Consign_DATANEXT  WHILE

    close SM_Consign_DATANEXT
    deallocate SM_Consign_DATANEXT
----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











--------------------------------------------------------------------

CREATE PROCEDURE STORELEDGER_XIAN(@STOREID varchar(8) ,                        -----如果为0000则全部仓库
                                                           @YYYYMM  varchar(8),      --------为当前会计期间
						           @LCODE  varchar(10),             ---如果LCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSCODE  varchar(20),             ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSNAME  varchar(20),             ---如果GOODSNAME  为‘GGGG’表示不对类别进行查询
						           @SpecName  varchar(20),             ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
						           @ModelNAME  varchar(20)             ---如果GOODSNAME  为‘GGGG’表示不对类别进行查询
                        
                                                      )   --APSOFTENCRYPTION       WITH ENCRYPTION
as



Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @WHERESTING   varchar(1800),
        @STOREIDSTR   varchar(100),
        @DBSTING   varchar(100)
                   set @now_date=(select   max(billDATE)   FROM DETAILBILLFLOW)

--@WHERESTR='  and 1=1 '
		if     NOT (@LCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = '  AND   I.GOODSID IN ( select G.GOODSID from GoodsTypetree T, GOODS G where T.indirect_no = '+CHAR(39)+@LCODE+CHAR(39)+ '  AND T.self_no=G.LCODE )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  ='     '
 		END
		if     NOT (@GOODSCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  CODE LIKE   '+CHAR(39)+'%'+@GOODSCODE+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  =@WHERESTING+'     '
 		END
		if     NOT (@GOODSNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  NAME LIKE   '+CHAR(39)+'%'+@GOODSNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END

		if     NOT (@SpecName='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  NAME LIKE   '+CHAR(39)+'%'+@SpecName+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END

		if     NOT (@ModelName='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  NAME LIKE   '+CHAR(39)+'%'+@ModelName+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END


		if     NOT (@STOREID='0000')
                           BEGIN
	                           SELECT    @STOREIDSTR   = '  AND   STOREID =  '+CHAR(39)+@STOREID+CHAR(39)
                           END
                           ELSE
                           BEGIN
			SELECT    @STOREIDSTR   = '     '
 		END
----------------------------------------------------


Create Table #temptable10
      (GOODSID  varchar(10) ,
	    CODE  varchar(30) ,
	  EQTY NUMERIC(20,6)  NULL, 
	  MEQTY NUMERIC(20,6)  NULL, 
	  EPRICE NUMERIC(20,6)  NULL, 
	  EAMOUNT NUMERIC(20,2)  NULL 
		)

----------------------------------------------------
----------------------------------------------------
		SELECT @SQLSTR='	 select  I.GOODSID, I.CODE,      '
		SELECT @SQLSTR=@SQLSTR+' E.EQTY,E.MEQTY,E.EPRICE,E.EAMOUNT '   --期末数量
		SELECT @SQLSTR=@SQLSTR+' from Goods  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,EQTY,MEQTY,EPRICE,EAMOUNT '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 2    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)  +@STOREIDSTR                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID  '
------------------------以上部分是取当前库存
                SELECT @SQLSTR=@SQLSTR+'  where     I. GOODSID in (select GOODSID from DETAILBILLFLOW where YYYYMM >='+char(39)+@YYYYMM+char(39)+@STOREIDSTR+')'  + @WHERESTING 
		SELECT @SQLSTR=@SQLSTR+'          order by  I.CODE                '
------------------------------------------------------------------------

		INSERT INTO  #temptable10  EXEC(@SQLSTR)

			SELECT GOODSID,EQTY,EPRICE,EAMOUNT,MEQTY  FROM  #temptable10   WHERE   EQTY <>0  ORDER BY CODE 










----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG















--------------------------------------------------------------------
--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[STOREYYYYMMDD](@STOREID varchar(8) ,                        -----如果为0000则全部仓库
                                                                                            @Begin_Date   varchar(10) ,
                                                                                           @End_date   varchar(10) ,  
                                                                                           @YYYYMM  varchar(8),      --------为当前会计期间
                                                                                           @DBFLAG  int ,     --------同价调拨标志   1代表包含  0 代表不包含
						           @LCODE  varchar(10),             ---如果LCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSCODE  varchar(20),             ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSNAME  varchar(20),             ---如果GOODSNAME  为‘GGGG’表示不对类别进行查询
                                                                                           @INF_COSTINGTYPEID   smallint ,     --------同价调拨标志   0  代表 不作为过滤条件
						           @modelNAME  varchar(20)             ---如果modelNAME  为‘GGGG’表示不对类别进行查询

                         
                                                      )     --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @WHERESTING   varchar(1800),
        @STOREIDSTR   varchar(100),
        @DBSTING   varchar(100)
                   set @now_date=(select   max(billDATE)   FROM DETAILBILLFLOW)
		
		IF @now_date IS NULL
		BEGIN
			SET @now_date='2030-12-12'
		END

--@WHERESTR='  and 1=1 '
                SELECT @DBSTING = '        '
		if     NOT (@LCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = '  AND   I.GOODSID IN ( select GOODSID from  GOODS  where Lcode like '+CHAR(39)+@LCODE+'%'+CHAR(39)+ ')'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  ='     '
 		END
		if     NOT (@modelNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  modelNAME LIKE   '+CHAR(39)+'%'+@modelNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END
		if     NOT (@GOODSCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  CODE LIKE   '+CHAR(39)+'%'+@GOODSCODE+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  =@WHERESTING+'     '
 		END
		if     NOT (@GOODSNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  NAME LIKE   '+CHAR(39)+'%'+@GOODSNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END
		if     NOT (@INF_COSTINGTYPEID=0)
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where INF_COSTINGTYPEID =  '+str(@INF_COSTINGTYPEID)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END
		if     NOT (@STOREID='0000')
                           BEGIN
	                           SELECT    @STOREIDSTR   = '  AND   STOREID =  '+CHAR(39)+@STOREID +CHAR(39)
                      		           select  @DBSTING   =@DBSTING+'      '                                             
                           END
                           ELSE
                           BEGIN
			SELECT    @STOREIDSTR   = '     '
	                         IF @DBFLAG=1
			BEGIN
                          		           select  @DBSTING   =@DBSTING+'   '                                             
			END
	                         IF @DBFLAG=0
			BEGIN
                          		           select  @DBSTING   =@DBSTING+'    AND    (not (BILLTYPE=5))  '   ---剔除调拨单
			END
 		END

----------------------------------------------------
		SELECT @SQLSTR='	 select  I.GOODSID, I.MQTYSPRICE,I.DSPRICETax,      '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)+ isnull(E.INQTY,0) -(isnull(BN.INQTY,0)- isnull(BN00.INQTY,0)) as BQTY, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0) -(isnull(BN.MINQTY,0)- isnull(BN00.MINQTY,0)) as MBQTY, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0) -(isnull(BN.INAMOUNT,0)- isnull(BN00.INAMOUNT,0)) as BAMOUNT, ' --期初金额
		SELECT @SQLSTR=@SQLSTR+'ISNULL(BE.INQTY,0)  AS INQTY   ,ISNULL(BE00.INQTY,0)  AS OUTQTY,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(BE.MINQTY,0)  AS MINQTY   ,ISNULL(BE00.MINQTY,0)  AS MOUTQTY,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(BE.INAMOUNT,0)  AS INAMOUNT  ,ISNULL(BE00.INAMOUNT,0)  AS OUTAMOUNT,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)+ isnull(E.INQTY,0) -(isnull(BN.INQTY,0)- isnull(BN00.INQTY,0))'
		SELECT @SQLSTR=@SQLSTR+'+ isnull(BE.INQTY,0)-isnull(BE00.INQTY,0) as EQTY ,' --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0) -(isnull(BN.MINQTY,0)- isnull(BN00.MINQTY,0))'
		SELECT @SQLSTR=@SQLSTR+'+ isnull(BE.MINQTY,0)-isnull(BE00.MINQTY,0) as MEQTY ,' --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0) -(isnull(BN.INAMOUNT,0)- isnull(BN00.INAMOUNT,0)) '
                           SELECT @SQLSTR=@SQLSTR+'+ISNULL(BE.INAMOUNT,0)-ISNULL(BE00.INAMOUNT,0)       as EAMOUNT '--期初金额
		 SELECT @SQLSTR=@SQLSTR+' from Goods  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(INQTY*INOUTFLAG)  as INQTY ,sum(MINQTY*INOUTFLAG)  as MINQTY ,sum(round(INQTY*INOUTFLAG*INPRICE,2))  as INAMOUNT'             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)  +@STOREIDSTR                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(BQTY) as BQTY ,sum(MBQTY) as MBQTY,SUM(BAMOUNT)  AS BAMOUNT'
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) +@STOREIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID  '
------------------------以上部分是取当前库存
		SELECT @SQLSTR=@SQLSTR+'  left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(INQTY) as INQTY ,sum(MINQTY) as MINQTY  ,sum(round(INQTY*INPRICE,2))  as INAMOUNT      '
		SELECT @SQLSTR=@SQLSTR+'  from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+ @Now_Date+char(39) +'  AND INOUTFLAG =1'  +@DBSTING +@STOREIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as BN on BN.GOODSID = I.GOODSID'  
		SELECT @SQLSTR=@SQLSTR+'  left outer join '
		SELECT @SQLSTR=@SQLSTR+'  (  '
		SELECT @SQLSTR=@SQLSTR+'select GOODSID,sum(INQTY) as INQTY ,sum(MINQTY) as MINQTY   ,sum(round(INQTY*INPRICE,2))  as INAMOUNT      '
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+ @Now_Date +char(39) +' AND INOUTFLAG =-1 '  +@DBSTING +@STOREIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BN00 on BN00.GOODSID = I.GOODSID  '
------------------------以上部分为取begin_date到Now_Date的库存
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(INQTY) as INQTY  ,sum(MINQTY) as MINQTY ,sum(round(INQTY*INPRICE,2))  as INAMOUNT      '
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+@End_Date+char(39)+' AND INOUTFLAG =1 ' +@DBSTING +@STOREIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE on BE.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(INQTY) as INQTY ,sum(MINQTY) as MINQTY  ,sum(round(INQTY*INPRICE,2))  as INAMOUNT      '
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+@End_Date +char(39)+'AND INOUTFLAG =-1'  +@DBSTING +@STOREIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE00 on BE00.GOODSID = I.GOODSID  '
                          SELECT @SQLSTR=@SQLSTR+'  where     I. GOODSID in (select GOODSID from DETAILBILLFLOW where YYYYMM >='+char(39)+@YYYYMM+char(39)+@STOREIDSTR+')'  + @WHERESTING 
		SELECT @SQLSTR=@SQLSTR+'          order by  I.CODE                '   
------------------------------------------------------------------------
		EXEC(@SQLSTR)

----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG
































----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_CGDD]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @VENDORFlag int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ITEMNO varchar(15)               --明细存货编号
declare @YunShuDWID varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号、
declare @VENDORID varchar(15)               --明细存货编号、
declare @INStoreID varchar(15)               --明细存货编号、
declare @SUMAMT  NUMERIC(20,10)               --明细存货编号、
declare @RATE  NUMERIC(20,10)               --明细存货编号、
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @STOREIDEqty NUMERIC(20,10)                          --仓库数量
declare @REFqty NUMERIC(20,10)                          --数量
declare @UNITqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @PRICETYPE  NUMERIC(20,10)               --含税单价
declare @KEYONGQTY  NUMERIC(20,10)               --含税单价
declare @TAXRATE NUMERIC(20,10)               --含税单价
declare @APRICE  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID  varchar(50)
declare @GOODSNAME varchar(30)                     --序列号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @REITEMNO VARCHAR(25)
declare @BILLDATE DATEtime
declare @SFLAG  INTEGER
declare @YYYYMM_FLAG  INTEGER
declare @count  INTEGER
declare @MaxRate  NUMERIC(20,10)               --含税单价
declare @MinRate  NUMERIC(20,10)               --含税单价
declare @DMinSPrice NUMERIC(20,10)               --含税单价

declare @STOREHSFS   INTEGER
declare @ZhongLiangXZ   INTEGER
declare @XSPriceXZ   INTEGER
declare @NEGCLOSEOFF   bit
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @JianShu [int] 
declare @MeiJianQty [T_QUANTITY] 
declare @LingTou [T_QUANTITY] 

       SELECT    @NEGCLOSEOFF=(SELECT  NEGCLOSEOFF  FROM   ACCINFO    WHERE   GUID='0001' )           

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )  
         


set @BILLID   = ltrim(rtrim(@BILLID))
SET  @RETURNSTRING='  '
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @ZhongLiangXZ   = (select optionvalue from accoptions where optionname ='ZhongLiangXZ')     
     set @XSPriceXZ   = (select optionvalue from accoptions where optionname ='XSPriceXZ')     

     set @BillDate =   (select BillDate  from STORECGDDM where rtrim(BILLID) = @BILLID)

    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 


      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END


if  (select isnull(flagPost,0) from STORECGDDM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CGDD   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STORECGDDM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STORECGDDM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STORECGDDM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STORECGDDM where rtrim(BILLID) = @BILLID)
     set @VENDORID =   (select VENDORID  from STORECGDDM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STORECGDDM where rtrim(BILLID) = @BILLID)
-----------@SFLAG  是否留货 1为留货
     set @INStoreID =   (select PAYTYPEID  from  STORECGDDM where rtrim(BILLID) = @BILLID)   ---------收款银行

     set @VENDORFLAG =   (select  ISNULL(VENDORFLAG,1)   from STORECGDDM where rtrim(BILLID) = @BILLID)


   	 SELECT @SUMAMT= (SELECT SUM(ROUND(DISC*0.01*unitprice*UNITQTY*(1+ISNULL(TAXRATE,0)*0.01),2)) FROM   STORECGDDD  where rtrim(BILLID) = @BILLID)
   	 SELECT @SUMAMT=0


                                      IF NOT (exists (select * from ViewVENDOR where VENDORID=@VENDORID   and VENDORFLAG=@VENDORFLAG))
                                     BEGIN
			      rollback transaction  trans_CGDD 
			      set @flagreturn = 0
                                              SET @RETURNSTRING='供应商不能为空或供应商不存在，单据不能记帐'
                                          RETURN
			END


   update  STORECGDDM  set  flagPost = 1,YYYYMM =@BILLYYYYMM   ,SUMAMT=VendorHKSum ,INVOICEAMT=0  ,STATUS=0        where ltrim(rtrim(BILLID)) = @BILLID 
   update  STORECGDDD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)          where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STORECGDDD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)   where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CGDD
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CGDD
      set @flagreturn = 0
   end
end
----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG
























----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_CGDD_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare  @INF_COSTINGTYPEID  INT
declare  @VENDORFlag  INT
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @VENDORID varchar(10)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @ChaCheSID VARCHAR(25)
declare @INSTOREID    varchar(15)               --明细存货编号

declare @STOREID    varchar(15)               --明细存货编号
declare @REDetailBillFlowID   varchar(30)                     --序列号
declare @REITEMNO   varchar(30)                     --序列号
declare @QUANTITY   NUMERIC(20,10)                     --序列号
declare @STATUS INT
declare @UNITQTY   NUMERIC(20,10)                     --序列号
declare @BILLTYPE   INTEGER
declare @SFLAG   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

                                              SET @RETURNSTRING='   '


	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STORECGDDM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STORECGDDM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CGDD_DEL   --事物开始

     set @BillType =   (select BillType  from STORECGDDM where rtrim(BILLID) = @BILLID)
     set @INStoreID =   (select PAYTYPEID  from  STORECGDDM where rtrim(BILLID) = @BILLID)   ---------收款银行
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STORECGDDM where rtrim(BILLID) = @BILLID)
	     set @STATUS =   (select  ISNULL(STATUS,0)  from STORECGDDM where rtrim(BILLID) = @BILLID)

			IF exists(select *  FROM  STORECGRKM  where rtrim(BILLID) = @BILLID   AND SUBSTRING(@BILLID,1,2)='CD')
			BEGIN
                              SET @RETURNSTRING=' 此订单已经被采购入库单引用不能取消记帐  '
			      rollback transaction trans_CGDD_DEL
			      set @flagreturn = 0
                                         RETURN
			END


			IF   @STATUS=1  
             		             BEGIN
                                              SET @RETURNSTRING=' 此订单已经完成不能取消记帐  '
			      rollback transaction trans_CGDD_DEL
			      set @flagreturn = 0
                                         RETURN
			END

			----如果订单已经被引用则不能取消记帐





   update  STORECGDDM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CGDD_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CGDD_DEL
      set @flagreturn = 0
   end
end















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG










--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[STORE_CGFK]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @REBILLID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @REBILLTYPE int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。


declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)

declare @bill_type int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @BANKID varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @VENDORID   varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @CLIENTID varchar(15)               --明细存货编号
declare @qty NUMERIC(20, 8)                          --数量
declare @SUMAMT NUMERIC(20, 8)                          --数量
declare @refqty NUMERIC(20, 8)                          --数量
declare @PRICE  NUMERIC(20, 8)               --含税单价
declare @AMT  NUMERIC(20, 8)               --含税单价
declare @MianAMT  NUMERIC(20, 8)               --含税单价
declare @VendorFLAG  int                    ---是否现款标志

declare @BATCHCODE varchar(30)                     --序列号
declare @VALIDDATE DATEtime



declare @BILLTYPE INTEGER

declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @MINBILLDATE DATEtime
declare @MAXBILLDATE DATEtime
declare @PRODUCTDATE DATEtime
declare @B_CODE VARCHAR(25)
declare @V_DATE DATEtime
declare @B_ID INTEGER
declare @SFKTYPE INTEGER
declare @STOREHSFS   INTEGER
declare @YYYYMM_FLAG  INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

   declare  @PREV_YYYYMM          varchar(6)  -- 上一个会计年月
   declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     

     set @BillDate =   (select BillDate  from STORECGFKM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END



if  (select isnull(flagPost,0) from STORECGFKM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CGFK   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STORECGFKM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STORECGFKM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STORECGFKM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STORECGFKM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  SFLAG  from STORECGFKM where rtrim(BILLID) = @BILLID)
     set @VENDORID =   (select  VENDOR_client_id  from STORECGFKM where rtrim(BILLID) = @BILLID)
     set @SFKTYPE =   (select  isnull(SFKTYPE,0)  from STORECGFKM where rtrim(BILLID) = @BILLID)
     set @BANKID =   (select  BANKID  from STORECGFKM where rtrim(BILLID) = @BILLID)
     set @VendorFLAG =   (select  ISNULL(VendorFLAG,1)  from STORECGFKM where rtrim(BILLID) = @BILLID)

		IF   @SFKTYPE=0
		begin
			      rollback transaction trans_CGFK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='付款类型不能为空，单据不能记帐'
                                          RETURN
		end

                                      IF NOT (exists (select * from VENDOR where VENDORID=@VENDORID))
                                     BEGIN
			      rollback transaction trans_CGFK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='供应商不能为空或供应商不存在，单据不能记帐'
                                          RETURN
			END
		IF   @SFKTYPE  IN (1,2)    ---@SFKTYPE =3   为不记录
		begin

                             IF NOT (exists (select * from BANK where BANKID=@BANKID))
                              BEGIN
			      rollback transaction trans_CGFK
			      set @flagreturn = 0
                                   SET @RETURNSTRING='银行科目不能为空或银行科目不存在，单据不能记帐'
                                   RETURN
	  		     END
		END


		IF  (@VendorFLAG=0) AND  (@SFKTYPE  IN (2,3))   
		begin

			      rollback transaction trans_CGFK
			      set @flagreturn = 0
                              SET @RETURNSTRING='当供应商为客户核算主体时，付款类型只能选择应付账款，否则单据不能记帐！'
                              RETURN
		END


   	 SELECT @SUMAMT= (SELECT AMT  FROM  STORECGFKM   where rtrim(BILLID) = @BILLID)
   	 SELECT @MianAMT= (SELECT ISNULL(MianAMT,0)  FROM  STORECGFKM   where rtrim(BILLID) = @BILLID)

	IF  @VendorFLAG=1
	BEGIN

            IF   (not exists(select *  from VENDORBILLFLOW  where 
             		                                    (rtrim(VENDORID) = @VENDORID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN
             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,0,Null,
		     @inoutFlag,0  )    
            END      ------IF   END
             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,@SUMAMT,Null,
		     -1,0  )    
	IF   @SFKTYPE  =3    ---@SFKTYPE =3   为不记录
	begin
             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,-@SUMAMT,Null,
		     -1,0  )    

	end



		IF @MianAMT <>0
		Begin

             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode+'免付金额',@VENDORID,
		     0,@MianAMT,Null,
		     -1,0  )    

		END
-------------------------------增加应收帐款  是 INOUTFLAG为1

-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM

	end      ------------IF  @VendorFLAG=1



	IF  @VendorFLAG=0
	BEGIN
	      SET @ClientID=@VendorID
	            IF   (not exists(select *  from CLIENTBILLFLOW  where 
             		                                    (rtrim(CLIENTID) = @CLIENTID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@CLIENTID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END


             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE, CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode, @CLIENTID,
		     0,@SUMAMT,Null,
		     1,0 )    
-------------------------------增加应收帐款  是 INOUTFLAG为1

             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE, CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode+'免付金额', @CLIENTID,
		     0,@MianAMT,Null,
		     1,0 )    
-------------------------------增加应收帐款  是 INOUTFLAG为1


                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM
	END         ----------IF  @VendorFLAG=0












------------------------------以下是解决科目帐的算法
	IF   @SFKTYPE  IN (1,2)    ---@SFKTYPE =3   为不记录
	begin

            IF   (not exists(select *  from BANKBILLFLOW  where 
             		                                    (rtrim(BANKID) = @BANKID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,0,Null,
		     @inoutFlag,0  )    
            END      ------IF   END
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,@SUMAMT,Null,
		     -1,0  )    
                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM
	end

    declare SM_Consign_CGFK Cursor for Select  REBILLID,REBILLTYPE,isnull(AMT,0)   as amt     from STORECGFKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CGFK

    fetch SM_Consign_CGFK into @REBILLID,@REBILLTYPE,@AMT

    while @@fetch_status = 0            ----开始
    begin

--	//  1,7
	    IF  @REBILLTYPE= 1  
	    BEGIN
		UPDATE   STORECGRKM   SET DISCAMT= isnull(DISCAMT,0)+@AMT   WHERE BILLID=@REBILLID 
	    END 
	    IF  @REBILLTYPE= -2
	    BEGIN
		UPDATE   VENDOR  SET SURAMT= isnull(SURAMT,0)+@AMT   WHERE  VENDORID=@REBILLID 

	    END 

	    fetch SM_Consign_CGFK into @REBILLID,@REBILLTYPE,@AMT

    END

    close SM_Consign_CGFK
    deallocate SM_Consign_CGFK



   update  STORECGFKM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CGFK
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CGFK
      set @flagreturn = 0
   end
end







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[STORE_CGFK_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @REBILLID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @BANKID    varchar(15)               --明细存货编号
declare @BATCHCODE   varchar(30)                     --序列号
declare @VENDORID   varchar(30)                     --序列号
declare @INF_COSTINGTYPEID   INT
declare @REBILLTYPE   INT
declare @REFQTY   NUMERIC(20, 8)
declare @AMT  NUMERIC(20, 8)
declare @STOREHSFS   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STORECGFKM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STORECGFKM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CGFK_DEL   --事物开始


	     set @VENDORID =   (select  VENDOR_CLIENT_ID  from STORECGFKM where rtrim(BILLID) = @BILLID)

	     set @BANKID =   (select  BANKID  from STORECGFKM where rtrim(BILLID) = @BILLID)

		DELETE   VENDORBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=8

                            execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM

		DELETE   BANKBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=8

                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM

    declare SM_Consign_CGFK_DEL Cursor for Select  REBILLID,REBILLTYPE, isnull(AMT,0)  as AMT     from STORECGFKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CGFK_DEL

    fetch SM_Consign_CGFK_DEL into @REBILLID,@REBILLTYPE,@AMT

    while @@fetch_status = 0            ----开始
    begin

--	//  1,7
	    IF  @REBILLTYPE= 1  
	    BEGIN
		UPDATE   STORECGRKM   SET DISCAMT= isnull(DISCAMT,0)-@AMT   WHERE BILLID=@REBILLID 
	    END 
	    IF  @REBILLTYPE= -2
	    BEGIN
		UPDATE   VENDOR  SET SURAMT= isnull(SURAMT,0)-@AMT   WHERE  VENDORID=@REBILLID 

	    END 


	    fetch SM_Consign_CGFK_DEL into @REBILLID,@REBILLTYPE,@AMT

    END
    close SM_Consign_CGFK_DEL
    deallocate SM_Consign_CGFK_DEL




   update  STORECGFKM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CGFK_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CGFK_DEL
      set @flagreturn = 0
   end
end





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG










CREATE PROCEDURE [dbo].[STORE_CGFP]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---是否现款标志
declare @VENDORFLAG int           ---单据对供应商精确运算标志
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @VENDORID   varchar(15)               --明细存货编号
declare @MakeMan   varchar(15)               --明细存货编号
declare @invoiceCode  varchar(200)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20, 8)                          --数量
declare @SUMAMT NUMERIC(20, 8)                          --单据总金额
declare @REBILLID varchar(15)
declare @REBILLSUMAMT NUMERIC(20,2)                          --引用数量
declare @REBILLDISCAMT NUMERIC(20,2)                          --引用数量
declare @AMT NUMERIC(20,2)                          --引用数量

declare @refqty NUMERIC(20, 8)                          --引用数量
declare @PRICE  NUMERIC(20, 8)               --含税单价
declare @APRICE  NUMERIC(20, 8)               --含税单价
declare @RATE  NUMERIC(20, 8)               --含税单价
declare @BATCHCODE varchar(30)                     --序列号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @UNITID VARCHAR(25)
declare @BILLDATE DATEtime
declare @invoiceDate DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @invoiceFlag  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @PRICEQX   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间


       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

     set @BillDate =   (select BillDate  from STORECGFPM where rtrim(BILLID) = @BILLID)
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     

      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END

if  (select isnull(flagPost,0) from STORECGFPM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CGFP   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STORECGFPM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STORECGFPM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STORECGFPM where rtrim(BILLID) = @BILLID)
     set @MakeMan =   (select MakeMan  from STORECGFPM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STORECGFPM where rtrim(BILLID) = @BILLID)
     set @VENDORID =   (select  VENDOR_CLIENT_ID  from STORECGFPM where rtrim(BILLID) = @BILLID)
     set @invoiceCode =   (select invoiceCode  from STORECGFPM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @invoiceDate =   (select invoiceDate  from STORECGFPM where rtrim(BILLID) = @BILLID)
     set @invoiceFlag =   (select  ISNULL(invoiceFlag,1)  from STORECGFPM where rtrim(BILLID) = @BILLID)


--------------------------------------------------

----REBILLSUMAMT  单据总额
----REBILLDISCAMT  已开票
----AMT   本次开票

    declare SM_Consign_CGFP Cursor for Select  ITEMNO,REBILLID, REBILLSUMAMT,REBILLDISCAMT,ISNULL(AMT,0) as AMT 
                                                                       from STORECGFPD where rtrim(BILLID) = @BILLID AND ISNULL(AMT,0)<>0

    Open SM_Consign_CGFP

    fetch SM_Consign_CGFP into @ITEMNO,@REBILLID, @REBILLSUMAMT,@REBILLDISCAMT,@AMT

    while @@fetch_status = 0            ----开始
    begin


	          UPDATE    STORECGRKM     set    FaPiaoAMT=ISNULL(FaPiaoAMT,0)+@AMT,invoiceCode=ISNULL(invoiceCode,'')+'  '+ISNULL(@invoiceCode,''),
					invoiceDate=@invoiceDate,invoiceFlag=@invoiceFlag
             		           WHERE rtrim(BILLID) = @REBILLID

	  
	          UPDATE    STORECGRKM     set    STATUS=1
             		           WHERE FaPiaoAMT = SumAMT and YaoPiaoFlag=1


--------------------
    fetch SM_Consign_CGFP into @ITEMNO,@REBILLID, @REBILLSUMAMT,@REBILLDISCAMT,@AMT

    END           ------- SM_Consign_CGFP  WHILE

    close SM_Consign_CGFP
    deallocate SM_Consign_CGFP

-----------------------以上是解决仓库记帐问题，以下是应付帐款的问题
-----------------------------
   update  STORECGFPM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CGFP
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CGFP
      set @flagreturn = 0
   end
end








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG









CREATE PROCEDURE [dbo].[STORE_CGFP_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @invoiceCode varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @BATCHCODE   varchar(30)                     --序列号
declare @VENDORID   varchar(30)                     --序列号
declare @INF_COSTINGTYPEID   INT
declare @VENDORFLAG   INT
declare @AMT NUMERIC(20,2)                          --引用数量
declare @billtype   INT
declare @SFLAG   INT
declare @REFQTY   NUMERIC(20, 8)
declare @STOREHSFS   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @REBILLSUMAMT NUMERIC(20,2)                          --引用数量
declare @REBILLDISCAMT NUMERIC(20,2)                          --引用数量
declare @invoiceDate DATEtime
declare @invoiceFlag  INTEGER
declare @REBILLID varchar(15)
declare @ITEMNO varchar(15)               --明细存货编号

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDate =  (select BILLDate  from STORECGFPM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
       IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STORECGFPM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CGFP_DEL   --事物开始

	SELECT @VENDORID=VENDOR_CLIENT_ID    FROM STORECGFPM  where rtrim(BILLID) = @BILLID 
	     set @BillType =   (select BillType  from STORECGFPM where rtrim(BILLID) = @BILLID)
     set @invoiceCode =   (select invoiceCode  from STORECGFPM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @invoiceDate =   (select invoiceDate  from STORECGFPM where rtrim(BILLID) = @BILLID)
     set @invoiceFlag =   (select  ISNULL(invoiceFlag,1)  from STORECGFPM where rtrim(BILLID) = @BILLID)



    declare SM_Consign_CGFP_DEL Cursor for Select  ITEMNO,REBILLID, REBILLSUMAMT,REBILLDISCAMT,ISNULL(AMT,0) as AMT 
                                                                       from STORECGFPD where rtrim(BILLID) = @BILLID AND ISNULL(AMT,0)<>0

    Open SM_Consign_CGFP_DEL

    fetch SM_Consign_CGFP_DEL into @ITEMNO,@REBILLID, @REBILLSUMAMT,@REBILLDISCAMT,@AMT

    while @@fetch_status = 0            ----开始
    begin
	          UPDATE    STORECGRKM     set    FaPiaoAMT=ISNULL(FaPiaoAMT,0)-@AMT,
			invoiceCode=substring(invoiceCode,1,charindex(@invoiceCode,invoiceCode) -1) + 
			substring(invoiceCode,charindex(@invoiceCode,invoiceCode)+ len(@invoiceCode) ,len(invoiceCode)), 
					invoiceDate=NULL,invoiceFlag=@invoiceFlag
             		           WHERE rtrim(BILLID) = @REBILLID
	  

	          UPDATE    STORECGRKM     set    STATUS=0
             		           WHERE FaPiaoAMT <> SumAMT and YaoPiaoFlag=1
--------------------
    fetch SM_Consign_CGFP_DEL into @ITEMNO,@REBILLID, @REBILLSUMAMT,@REBILLDISCAMT,@AMT

    END           ------- SM_Consign_CGFP_DEL  WHILE

    close SM_Consign_CGFP_DEL
    deallocate SM_Consign_CGFP_DEL

                             DELETE   DetailBillFlow     WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 AND BILLTYPE=@billtype
--------------------------------------以上上全部删除单据  是解决多次记帐失败的问题

   update  STORECGFPM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CGFP_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CGFP_DEL
      set @flagreturn = 0
   end
end








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG




































--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[STORE_CGRK]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare                   @RETURNSTRING00            varchar(60)       ---单据编号   
declare                   @flagreturn00 int      ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
declare @SFLAG  int                    ---是否现款标志
declare @VendorFLAG  int                    ---是否现款标志
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @VENDORID   varchar(15)               --明细存货编号
declare @YunShuDWID   varchar(15)               --明细存货编号
declare @BuMenID   varchar(15)               --明细存货编号
declare @ClientID   varchar(15)               --明细存货编号
declare @bankID   varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @REDetailBillFlowID varchar(15)               --明细存货编号
declare @GJRKDetailBillFlowID varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @UNITqty NUMERIC(20,10)                          --数量
declare @SUMAMT NUMERIC(20,10)                          --单据总金额
declare @TAXRATE NUMERIC(20,10)                          --单据总金额
declare @RATE NUMERIC(20,10)                          --单据总金额
declare @refqty NUMERIC(20,10)                          --引用数量
declare @KEYONGqty NUMERIC(20,10)                          --引用数量
declare @UNITPRICE NUMERIC(20,10)                          --引用数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @YunFeiFT  NUMERIC(20,10)               --含税单价
declare @BILLTYPE INTEGER
declare @PRICETYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLCODE00 VARCHAR(25)
declare @BILLID00 VARCHAR(25)
declare @ITEMNO00 VARCHAR(25)
declare @MAKEMAN VARCHAR(25)
declare @ChaCheSID VARCHAR(25)
declare @PanYunSID VARCHAR(25)
declare @REITEMNO varchar(15)               --明细存货编号
declare @KEYONGunitQTY  NUMERIC(20,10)               --含税单价
declare @KEYONGquantity  NUMERIC(20,10)               --含税单价
declare @TMPunitQTY  NUMERIC(20,10)               --含税单价
declare @TMPquantity  NUMERIC(20,10)               --含税单价

declare @YunFeiZhiFuFX VARCHAR(25)  ----运费支付方向
declare @ChaChePrice  NUMERIC(20,10)               --含税单价
declare @PanYunPrice  NUMERIC(20,10)               --含税单价
declare @ChaCheSYunfei  NUMERIC(20,10)               --含税单价
declare @PanYunSYunfei  NUMERIC(20,10)               --含税单价
declare @QiTaFeiYong  NUMERIC(20,10)               --含税单价
declare @YunFeiSum  NUMERIC(20,10)               --含税单价
declare @KEYONGSTOREID  VARCHAR(25)
declare @REGJRKITEMNO VARCHAR(25)
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @JianShu [int] 
declare @MeiJianQty [T_QUANTITY] 
declare @LingTou [T_QUANTITY] 

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

     set @BillDate =   (select BillDate  from STORECGRKM where rtrim(BILLID) = @BILLID)
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     

    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END

if  (select isnull(flagPost,0) from STORECGRKM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CGRK   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STORECGRKM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STORECGRKM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STORECGRKM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STORECGRKM where rtrim(BILLID) = @BILLID)
     set @BuMenID =   (select BuMenID  from  STORECGRKM where rtrim(BILLID) = @BILLID)   ---------收款银行
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STORECGRKM where rtrim(BILLID) = @BILLID)
     set @VendorFLAG =   (select  ISNULL(VendorFLAG,1)  from STORECGRKM where rtrim(BILLID) = @BILLID)
     set @VENDORID =   (select  VENDORID  from STORECGRKM where rtrim(BILLID) = @BILLID)
     set @BANKID =   (select BANKID  from STORECGRKM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @ChaCheSID =   (select ChaCheSID  from STORECGRKM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @PanYunSID =   (select PanYunSID  from STORECGRKM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @YunFeiZhiFuFX =   (select YunFeiZhiFuFX  from STORECGRKM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @ChaChePrice =   (select ISNULL(ChaChePrice,0)  from STORECGRKM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @PanYunPrice =   (select ISNULL(PanYunPrice,0)  from STORECGRKM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @ChaCheSYunFei=    (select ROUND(ISNULL(ChaChePrice,0)*SumQUANTITY,2) from STORECGRKM where rtrim(BILLID) = @BILLID)   ---------付款银行 
     set @PanYunSYunFei=    (select ROUND(ISNULL(PanYunPrice,0)*SumQUANTITY,2) from STORECGRKM where rtrim(BILLID) = @BILLID)   ---------付款银行 
     set @YunFeiSum=   @ChaCheSYunFei+@PanYunSYunFei
     set @QiTaFeiYong =   (select ISNULL(QiTaFeiYong,0)  from STORECGRKM where rtrim(BILLID) = @BILLID)   ---------付款银行

/*declare @ChaCheSID VARCHAR(25)
declare @PanYunSID VARCHAR(25)
declare @YunFeiZhiFuFX VARCHAR(25)  ----运费支付方向
declare @ChaChePrice  NUMERIC(20,10)               --含税单价
declare @PanYunPrice  NUMERIC(20,10)               --含税单价  */

                                
                              IF (NOT exists(select * from YunShuDW where YunShuDWID=@ChaCheSID)) and @ChaChePrice<>0
                              BEGIN
			      rollback transaction trans_CGRK
			      set @flagreturn = 0
                                      SET @RETURNSTRING='叉车商不能为空或叉车商不存在，单据不能记帐'
                                       RETURN
			END

                              IF (NOT exists(select * from YunShuDW where YunShuDWID=@PanYunSID)) and @PanYunPrice<>0
                              BEGIN
			      rollback transaction trans_CGRK
			      set @flagreturn = 0
                                      SET @RETURNSTRING='盘运商不能为空或盘运商不存在，单据不能记帐'
                                       RETURN
			END


                                      IF NOT (exists (select * from VIEWVENDOR where VENDORID=@VENDORID  and VendorFLAG=@VendorFLAG))
                                     BEGIN
			      rollback transaction trans_CGRK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='供应商不能为空或供应商不存在，单据不能记帐'
                                          RETURN
			END



                       IF @SFLAG=1 and @VendorFLAG=0
                       BEGIN
			      rollback transaction trans_CGRK
			      set @flagreturn = 0
                              SET @RETURNSTRING='当供应商为客户的时候，不允许选择现款采购，单据不能记帐'
                              RETURN
		       END



   	 SELECT @SUMAMT=0


    declare SM_Consign_CGRK Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(UNITPRICE,0)*ISNULL(DISC,0)*0.01 as PRICE, 
                                                                   DetailBillFlowID,ISNULL(UNITQTY,0)  as UNITQTY,REGJRKITEMNO,PRICETYPE,TAXRATE,ISNULL(YunFeiFT,0) as YunFeiFT,JianShu,MeiJianQty,LingTou,REITEMNO    from STORECGRKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CGRK

    fetch SM_Consign_CGRK into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE, @DetailBillFlowID,@UNITQTY,@REGJRKITEMNO,@PRICETYPE,@TAXRATE,@YunFeiFT,@JianShu,@MeiJianQty,@LingTou,@REITEMNO

    while @@fetch_status = 0            ----开始
    begin

-------缺少检测仓库  明日解决

                     set @MeiJianQty =   (select ISNULL(RATE1,0)  from GOODS where  GOODSID = @GOODSID)


                            IF (ISNULL(@JianShu,0)*ISNULL(@MeiJianQty,0)+ISNULL(@LingTou,0)<>@Unitqty) AND (ISNULL(@JianShu,0)<>0 OR ISNULL(@LingTou,0)<>0)
                           BEGIN
	  	      rollback transaction trans_CGRK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='件数*每件数量+零头与数量不等，单据不能记帐'
			    close SM_Consign_CGRK
			    deallocate SM_Consign_CGRK
                                          RETURN
			END

                                      IF NOT (exists (select * from STORE where STOREID=@STOREID))
                                     BEGIN
			      rollback transaction trans_CGRK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库不能为空或仓库不存在，单据不能记帐'
			    close SM_Consign_CGRK
			    deallocate SM_Consign_CGRK
                                          RETURN
			END




                                      IF exists (select * from STORE where STOREID=@STOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_CGRK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_CGRK
			    deallocate SM_Consign_CGRK
                                          RETURN
			END



            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)  from GOODS where  GOODSID = @GOODSID)

----------------订单处理引用begin

	IF @REITEMNO IS NOT NULL
    BEGIN
	         SELECT   @KEYONGunitQTY = UNITQTY-ISNULL(WCunitQTY,0)   FROM   STORECGDDD    WHERE  ITEMNO=@REITEMNO
	         SELECT   @KEYONGquantity = quantity-ISNULL(WCquantity,0)   FROM   STORECGDDD    WHERE  ITEMNO=@REITEMNO
        IF @KEYONGunitQTY >0  or @KEYONGquantity>0
		BEGIN
		   UPDATE   STORECGDDD   SET WCunitQTY=ISNULL(WCunitQTY,0)+ISNULL(@UNITQTY,0)  WHERE  ITEMNO=@REITEMNO
		   UPDATE   STORECGDDD   SET WCquantity=ISNULL(WCquantity,0)+ISNULL(@qty,0)  WHERE  ITEMNO=@REITEMNO
		   
			SELECT @TMPunitQTY=SUM(UNITQTY-isnull(WCunitQTY,0))  FROM STORECGDDD   WHERE  BILLID IN (SELECT BILLID FROM   STORECGDDD WHERE  ITEMNO=@REITEMNO)
			SELECT @TMPquantity=SUM(quantity-isnull(WCquantity,0))  FROM STORECGDDD   WHERE  BILLID IN (SELECT BILLID FROM   STORECGDDD WHERE  ITEMNO=@REITEMNO)
			IF @TMPunitQTY<=0  OR @TMPquantity <= 0
			BEGIN
			   UPDATE   STORECGDDM   SET STATUS=1  WHERE  BILLID IN (SELECT BILLID FROM   STORECGDDD WHERE  ITEMNO=@REITEMNO)
			END
		END
		ELSE
		BEGIN
			    set @flagreturn = 0
                SET @RETURNSTRING='引用的订单已经完成或终止，请重新修改单据'
			    close  SM_Consign_CGRK
			    deallocate  SM_Consign_CGRK
			    rollback transaction trans_CGRK
                RETURN
		END
	END

----------------订单处理引用end



---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	

	IF @PRICETYPE=1   
	BEGIN
   	 SELECT @SUMAMT=@SUMAMT+ROUND(@price*@QTY*(1+ISNULL(@TAXRATE,0)*0.01),2)
	END
	IF @PRICETYPE=0  
	BEGIN
   	 SELECT @SUMAMT=@SUMAMT+ROUND(@price*@UNITQTY*(1+ISNULL(@TAXRATE,0)*0.01),2)

		IF   @QTY<>0
		BEGIN
		SET  @PRICE=(@UNITQTY*@PRICE)/@QTY
		END

	END



-----------
	IF  @QTY<>0
	begin	
	set @PRICE=(@QTY*@PRICE+@YunFeiFT)/@QTY     -----增加运费分摊
	end
---------------
	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE  ,@DetailBillFlowID, @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT )
	    Values
---	    (@NEWID,@YYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	    (@NEWID,@BillYYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     isnull(@REFQTY,0),0)    
	          UPDATE   STORECGRKD  set    DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_CGRK


-----------====================2012-09-04 begin

	IF   @INF_COSTINGTYPEID=6 
	Begin

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT )
	    Values
---	    (@NEWID,@YYYYMM,2,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	    (@NEWID,@BILLYYYYMM,2,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     isnull(@REFQTY,0),0)    

	END

--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

--------------------
    fetch SM_Consign_CGRK into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE, @DetailBillFlowID,@UNITQTY,@REGJRKITEMNO,@PRICETYPE,@TAXRATE,@YunFeiFT,@JianShu,@MeiJianQty,@LingTou,@REITEMNO

    END           ------- SM_Consign_CGRK  WHILE

    close SM_Consign_CGRK
    deallocate SM_Consign_CGRK

----------------------------可能不需要下面的这几句代码
--------------------------------关键是生成一张新的冲回估价入库单其实很简单
--		  取得新的单据号，用insert  into 就可以完成关键是单据号
--------

                        IF exists (select * from STORECGRKD  where rtrim(BILLID) = @BILLID  AND  REGJRKITEMNO  IN (SELECT ITEMNO FROM STOREGJRKD ))
                        BEGIN
	             		    execute  GET_BILL_NO     'STOREGJRKM',@BILLDATE,'GR',@bill_no_selfd = @BILLCODE00 output
             			    execute  GETKEYVALUE     'STOREGJRKM',@R_KeyValue = @BILLID00 output

             	             			 INSERT  INTO STOREGJRKM   (BILLID,YYYYMM,CODE,MAKEMAN,BILLDATE,STATUS,MEMO,REFERBILLCODE,VENDORID)
		                                      VALUES (@BILLID00,@YYYYMM,@BILLCODE00,@MAKEMAN,@BILLDATE,1,@BILLCODE+'生成',@billid,@VENDORID)
----------------------------------------------------------------------以下是插入从表
		    declare SM_Consign_DATANEXT Cursor for Select  ITEMNO,GOODSID,STOREID,
                                                                   DetailBillFlowID,UNITQTY,QUANTITY,REGJRKITEMNO    from STORECGRKD   where rtrim(BILLID) = @BILLID   AND  REGJRKITEMNO  IN (SELECT ITEMNO   FROM STOREGJRKD )

		    Open   SM_Consign_DATANEXT

		    fetch  SM_Consign_DATANEXT into @ITEMNO,@GOODSID,@STOREID, @DetailBillFlowID,@UNITQTY,@QTY,@REGJRKITEMNO

		    while @@fetch_status = 0            ----开始
		    begin

             		    execute  GETKEYVALUE     'STOREGJRKD',@R_KeyValue = @ITEMNO00 output
			SELECT @UNITPRICE = UNITPRICE,@REDetailBillFlowID=@DetailBillFlowID  FROM STOREGJRKD  WHERE ITEMNO=@REGJRKITEMNO
		    insert into STOREGJRKD 
		    (BILLID, ITEMNO,UNITPRICE,STOREID,GOODSID,UNITQTY,QUANTITY,REDetailBillFlowID)
		    Values
		    (@BILLID00,@ITEMNO00 ,@UNITPRICE,@STOREID,@GOODSID ,-@UNITQTY,-@QTY,@REDetailBillFlowID )    

		    fetch  SM_Consign_DATANEXT into @ITEMNO,@GOODSID,@STOREID, @DetailBillFlowID,@UNITQTY,@QTY,@REGJRKITEMNO

		    END           ------- SM_Consign_DATANEXT  WHILE

		    close SM_Consign_DATANEXT
		    deallocate SM_Consign_DATANEXT


	                 execute  STORE_TALLY  @BILLID00 ,'STOREGJRKM',@RETURNSTRING00  OUTPUT,  @flagreturn00    output
             		    IF  @flagreturn00<>2
	                 BEGIN
		      rollback transaction trans_CGRK
		      set @flagreturn = 0
             		    RETURN
		    END
     END
-----------------------以上是解决仓库记帐问题，以下是应付帐款的问题

        set @SUMAMT=@SUMAMT+@QiTaFeiYong


        IF @YunFeiZhiFuFX='厂方垫付运费' 
        begin
        set @SUMAMT=@SUMAMT+@YunFeiSum
        end


        IF @YunFeiZhiFuFX='我方支付运费' 
        begin

                    IF  @ChaChePrice<>0
		    begin
			set @YunShuDWID=@ChaCheSID
	            IF   (not exists(select *  from YunShuDWBILLFLOW  where 
             		                                    (rtrim(YunShuDWID) = @YunShuDWID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@YunShuDWID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
	             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@YunShuDWID,
		     0,@ChaCheSYunFei,Null,
		     1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      YunShuDW_CACULATOR_YYYYMM   @YunShuDWID,@YYYYMM

		    end

                    IF  @PanYunPrice<>0
		    begin
			set @YunShuDWID=@PanYunSID


	            IF   (not exists(select *  from YunShuDWBILLFLOW  where 
             		                                    (rtrim(YunShuDWID) = @YunShuDWID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@YunShuDWID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
	             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@YunShuDWID,
		     0,@PanYunSYunFei,Null,
		     1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      YunShuDW_CACULATOR_YYYYMM   @YunShuDWID,@YYYYMM

		        end
        end   ------我方支付运费的情况
--------------------------------------------

	IF @SFLAG=0  and  @VendorFLAG=1
	BEGIN
	            IF   (not exists(select *  from VENDORBILLFLOW  where 
             		                                    (rtrim(VENDORID) = @VENDORID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
	             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,@SUMAMT,Null,
		     1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM

	END     ----------------     IF @SFLAG=0


	IF @SFLAG=0  and  @VendorFLAG=0
	BEGIN
	      SET @ClientID=@VendorID
	            IF   (not exists(select *  from CLIENTBILLFLOW  where 
             		                                    (rtrim(CLIENTID) = @CLIENTID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE, CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT  )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode, @CLIENTID,
		     0,0,Null,
		     @inoutFlag,0 )    
	            END      ------IF   END
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE, CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT,BuMenID   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode, @CLIENTID,
		     0,-@SUMAMT,Null,
		     1,0 ,@BuMenID )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM
	END         ---------------IF @SFLAG=0





------------------------------------2004-07-05--------------解决采购付款问题

	IF @SFLAG=1  AND  NOT( @BANKID='APSOFT')
	BEGIN
                                      IF NOT (exists (select * from BANK where BANKID=@BANKID))
                                     BEGIN
			      rollback transaction trans_CGRK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='银行科目不能为空或银行科目不存在，单据不能记帐'
                                          RETURN
			END


------------------------------以下是解决科目帐的算法

	            IF   (not exists(select *  from BANKBILLFLOW  where 
             		                                    (rtrim(BANKID) = @BANKID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
	             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
			    insert into BANKBILLFLOW 
			    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
			     BAMOUNT,INAMOUNT,OUTAMOUNT,
			     INOUTFLAG,EAMOUNT   )
			    Values
			    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
			     0,0,Null,
			     @inoutFlag,0  )    
	            END      ------IF   END
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,@SUMAMT,Null,
		     -1,0  )    
	                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM

         update  STORECGRKM  set DISCAMT=VendorHKSum       where ltrim(rtrim(BILLID)) = @BILLID 

	END  ---------------	IF @SFLAG=1
--------更新定价-------begin--------------
Insert into  CGRKGoodsPrice ([ID]      ,[BILLID]      ,[ITEMNO]   ,[STOREID]
      ,[GOODSID]      ,[PRICE]      ,[QUANTITY]      ,[MEMO]
      ,[TAXRATE]      ,[DISC]      ,[UNITPRICE]      ,[UNITQTY]
      ,[PRICETYPE]      ,[AMT]      ,[TAXAMT]      ,[YunFeiFT]
      ,[CaiZhi]      ,[ChanDi]      ,[AMOUNT]      ,[invoiceqty]
      ,[invoiceamt]      ,[InvoiceNow]      ,[SPECNameD]      ,[JianShu]
      ,[MeiJianQty]      ,[LingTou]      ,[FuZhuQTY]      ,[ZongLen])

 select BILLID+ITEMNO as  ID      ,[BILLID]      ,[ITEMNO]   ,[STOREID]
      ,[GOODSID]      ,[PRICE]      ,[QUANTITY]      ,[MEMO]
      ,[TAXRATE]      ,[DISC]      ,[UNITPRICE]      ,[UNITQTY]
      ,[PRICETYPE]      ,[AMT]      ,[TAXAMT]      ,[YunFeiFT]
      ,[CaiZhi]      ,[ChanDi]      ,[AMOUNT]      ,[invoiceqty]
      ,[invoiceamt]      ,[InvoiceNow]      ,[SPECNameD]      ,[JianShu]
      ,[MeiJianQty]      ,[LingTou]      ,[FuZhuQTY]      ,[ZongLen]
      from storecgrkd where BILLID=@BILLID
      
 update   CGRKGoodsPrice set CGRKGoodsPrice.VENDORID=storecgrkM.VENDORID,
 CGRKGoodsPrice.EMPID=storecgrkM.EMPID,
 CGRKGoodsPrice.BILLDATE=storecgrkM.BILLDATE,
 CGRKGoodsPrice.CODE=storecgrkM.CODE   from storecgrkM,CGRKGoodsPrice 
 where CGRKGoodsPrice.BILLID=storecgrkM.BILLID   and storecgrkM.BILLID=@BILLID
 --------更新理算系数---只有数量或者只有重量
 update   CGRKGoodsPrice set CGRKGoodsPrice.LSRate=Goods.Rate
   from GOODS,CGRKGoodsPrice 
 where CGRKGoodsPrice.GOODSID=GOODS.GOODSID   and CGRKGoodsPrice.BILLID=@BILLID
 AND (ISNULL(CGRKGoodsPrice.unitqty,0)=0 OR ISNULL(CGRKGoodsPrice.quantity,0)=0 )
 
  update   CGRKGoodsPrice set LSRate=quantity/unitqty
   from CGRKGoodsPrice  where  BILLID=@BILLID  and ISNULL(quantity,0)<>0 and ISNULL(unitqty,0)<>0

 update   CGRKGoodsPrice set unitqty=quantity/LSRate
   from CGRKGoodsPrice  where  BILLID=@BILLID  and ISNULL(unitqty,0)=0 and LSRate<>0
 
 update   CGRKGoodsPrice set quantity=unitqty*isnull(LSRate,0)
   from CGRKGoodsPrice  where  BILLID=@BILLID  and ISNULL(quantity,0)=0 

   update  CGRKGoodsPrice  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2) where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  CGRKGoodsPrice  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)   where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0

   update  CGRKGoodsPrice  set   CGDSPrice  =  unitprice where ltrim(rtrim(BILLID)) = @BILLID      AND PRICETYPE=1
   update  CGRKGoodsPrice  set   CGDSPrice  =  AMT/quantity where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0  and ISNULL(quantity,0)<>0
   
   update  CGRKGoodsPrice  set   CGMSPrice  =  unitprice where ltrim(rtrim(BILLID)) = @BILLID      AND PRICETYPE=0
   update  CGRKGoodsPrice  set   CGMSPrice  =  AMT/unitqty where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1  and ISNULL(unitqty,0)<>0
   update  CGRKGoodsPrice  set   DEQTY  =  quantity,MEQTY=unitqty 
 





--------更新定价-------end--------------



-----------------------------
   update  STORECGRKM  set  flagPost = 1,YYYYMM =@BILLYYYYMM ,SUMAMT=VendorHKSum ,INVOICEAMT=0           where ltrim(rtrim(BILLID)) = @BILLID 
     
   update  STORECGRKD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)          where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STORECGRKD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)   where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CGRK
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CGRK
      set @flagreturn = 0
   end
end


















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG















----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[STORE_CGRK_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare   @flagreturn00   int  ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @GJRKDetailBillFlowID  varchar(15)               --明细存货编号
declare @VENDORID   varchar(30)                     --序列号
declare @ClientID   varchar(30)                     --序列号
declare @VendorFLAG  int                    ---是否现款标志
declare @BILLIDGJRK   varchar(30)                     --序列号
declare @REITEMNO   varchar(30)                     --序列号
declare @INF_COSTINGTYPEID   INT
declare @billtype   INT
declare @SFLAG   INT
declare @REFQTY   NUMERIC(20,10)
declare @quantity   NUMERIC(20,10)
declare @unitqty   NUMERIC(20,10)
declare @ChaCheSID VARCHAR(25)
declare @PanYunSID VARCHAR(25)
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BillDate =   (select BillDate  from STORECGRKM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STORECGRKM where ltrim(rtrim(BILLID)) = @BILLID ) = 0 
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CGRK_DEL   --事物开始

	SELECT @VENDORID=VENDORID    FROM STORECGRKM  where rtrim(BILLID) = @BILLID 
     set @BillType =   (select BillType  from STORECGRKM where rtrim(BILLID) = @BILLID)
     set @VendorFLAG =   (select  ISNULL(VendorFLAG,1)  from STORECGRKM where rtrim(BILLID) = @BILLID)


			   IF exists (select * from STORECGFKD  where REBILLID= @BILLID  and rebilltype=1   )
			BEGIN
                                              SET @RETURNSTRING=' 此单据已经被采购付款单引用不能取消记帐！  '
			      rollback transaction trans_CGRK_DEL
			      set @flagreturn = 0
                                         RETURN
			END

			   IF exists (select * from STORECGFPD  where REBILLID= @BILLID     )
			BEGIN
                                              SET @RETURNSTRING=' 此单据已经被采购发票引用不能取消记帐！  '
			      rollback transaction trans_CGRK_DEL
			      set @flagreturn = 0
                                         RETURN
			END


    declare SM_Consign_CGRK_DEL Cursor for Select GOODSID,DetailBillFlowID,STOREID,BILLID,quantity ,REITEMNO,UNITQTY   from STORECGRKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CGRK_DEL

    fetch SM_Consign_CGRK_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@BILLID,@quantity,@REITEMNO,@UNITQTY

    while @@fetch_status = 0            ----开始
    begin
	            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)

----------------订单处理引用begin

	IF @REITEMNO IS NOT NULL
    BEGIN
		   UPDATE   STORECGDDD   SET WCunitQTY=ISNULL(WCunitQTY,0)-ISNULL(@UNITQTY,0)  WHERE  ITEMNO=@REITEMNO
		   UPDATE   STORECGDDD   SET WCquantity=ISNULL(WCquantity,0)-ISNULL(@QUANTITY,0)  WHERE  ITEMNO=@REITEMNO
  		   UPDATE   STORECGDDM   SET STATUS=0  WHERE  BILLID IN (SELECT BILLID FROM   STORECGDDD WHERE  ITEMNO=@REITEMNO)
	END

----------------订单处理引用end
                             DELETE   DetailBillFlow     WHERE  ID=@DetailBillFlowID
--------------------------------------以上是删除一条单据明细
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@STOREID AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
-------------------
    fetch SM_Consign_CGRK_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@BILLID,@quantity,@REITEMNO,@UNITQTY

    END           ------- SM_Consign_CGRK_DEL  WHILE

    close SM_Consign_CGRK_DEL
    deallocate SM_Consign_CGRK_DEL

                             DELETE   DetailBillFlow     WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND (YYYYMMBILL in (1,2)) AND BILLTYPE=@billtype
--------------------------------------以上上全部删除单据  是解决多次记帐失败的问题

----------------------------
	     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STORECGRKM where rtrim(BILLID) = @BILLID)
	     set @BANKID =   (select BANKID  from STORECGRKM where rtrim(BILLID) = @BILLID)   ---------付款银行


     set @ChaCheSID =   (select ChaCheSID  from STORECGRKM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @PanYunSID =   (select PanYunSID  from STORECGRKM where rtrim(BILLID) = @BILLID)   ---------付款银行


		DELETE   YunShuDWBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@BILLTYPE
    		         execute      YunShuDW_CACULATOR_YYYYMM   @ChaCheSID,@YYYYMM
    		         execute      YunShuDW_CACULATOR_YYYYMM   @PanYunSID,@YYYYMM


		SELECT @VENDORID =(SELECT VENDORID FROM STORECGRKM     where ltrim(rtrim(BILLID)) = @BILLID )
		
		IF @SFLAG=0   and  @VendorFLAG=1
		BEGIN
			DELETE   VENDORBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@BILLTYPE
             		               execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM
	                             DELETE  VENDORBILLFLOW    WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 AND BILLTYPE=@billtype
--------------------------------------以上上全部删除单据  是解决多次记帐失败的问题

		END     
		IF @SFLAG=0   and  @VendorFLAG=0
		BEGIN
		      SET @ClientID=@VendorID
	
				DELETE   CLIENTBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@billTYPE
                	            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM
	                             DELETE  CLIENTBILLFLOW   WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 AND BILLTYPE=@billtype
--------------------------------------以上上全部删除单据  是解决多次记帐失败的问题

		END     

		IF @SFLAG=1
		BEGIN
			DELETE BANKBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@BILLTYPE
	                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM
	                             DELETE  BANKBILLFLOW    WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 AND BILLTYPE=@billtype
		END
-----------------------------------------------
			
         DELETE  CGRKGoodsPrice    WHERE  ltrim(rtrim(BILLID)) = @BILLID 			

   update  STORECGRKM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CGRK_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CGRK_DEL
      set @flagreturn = 0
   end
end
----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG





















--------------------------------------------------------------------

CREATE PROCEDURE [STORE_CGTH]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @VENDORID   varchar(15)               --明细存货编号
declare @clientID   varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @bankid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @UNITqty NUMERIC(20,10)                          --数量
declare @SUMAMT NUMERIC(20,10)                          --数量
declare @STOREIDEQTY   NUMERIC(20,10)                          --数量
declare @RATE   NUMERIC(20,10)                          --数量
declare @refqty NUMERIC(20,10)                          --数量
declare @TAXRATE NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID varchar(30)                     --序列号
declare @GOODSNAME varchar(30)                     --序列号
declare @BILLTYPE INTEGER
declare @PRICETYPE INTEGER
declare @count INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @B_CODE VARCHAR(25)
declare @yyyymm_flag INTEGER
declare @STOREHSFS   INTEGER
declare @NEGCLOSEOFF   bit
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @JianShu [int] 
declare @MeiJianQty [T_QUANTITY] 
declare @LingTou [T_QUANTITY] 
       SELECT    @NEGCLOSEOFF=(SELECT  NEGCLOSEOFF  FROM   ACCINFO    WHERE   GUID='0001' )           


       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @BillDate =   (select BillDate  from STORECGTHM where rtrim(BILLID) = @BILLID)

      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END



if  (select isnull(flagPost,0) from STORECGTHM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CGTH   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STORECGTHM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STORECGTHM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STORECGTHM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STORECGTHM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select   ISNULL(SFLAG,0)   from STORECGTHM where rtrim(BILLID) = @BILLID)
     set @VENDORID =   (select  VENDORID  from STORECGTHM where rtrim(BILLID) = @BILLID)
     set @CLIENTID =   (select CLIENTID  from STORECGTHM where rtrim(BILLID) = @BILLID)    ----------收付款方式
     set @BANKID =   (select BANKID  from STORECGTHM where rtrim(BILLID) = @BILLID)   ---------付款银行


                                      IF NOT (exists (select * from VENDOR where VENDORID=@VENDORID))
                                     BEGIN
			      rollback transaction trans_CGTH
			      set @flagreturn = 0
                                              SET @RETURNSTRING='供应商不能为空或供应商不存在，单据不能记帐'
                                          RETURN
			END
   	 SELECT @SUMAMT=0


    declare SM_Consign_CGTH Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(UNITPRICE,0)*ISNULL(DISC,0)*0.01 as PRICE, 
                                                                   DetailBillFlowID,REDetailBillFlowID,ISNULL(UNITQTY,0)  as UNITQTY,PRICETYPE,TAXRATE,JianShu,MeiJianQty,LingTou    from STORECGTHD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CGTH

    fetch SM_Consign_CGTH into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE, @DetailBillFlowID,@REDetailBillFlowID,@UNITQTY,@PRICETYPE,@TAXRATE,@JianShu,@MeiJianQty,@LingTou

    while @@fetch_status = 0            ----开始
    begin

                     set @MeiJianQty =   (select ISNULL(RATE1,0)  from GOODS where  GOODSID = @GOODSID)


                            IF (ISNULL(@JianShu,0)*ISNULL(@MeiJianQty,0)+ISNULL(@LingTou,0)<>@Unitqty) AND (ISNULL(@JianShu,0)<>0 OR ISNULL(@LingTou,0)<>0)
                                     BEGIN
			      rollback transaction trans_CGTH
			      set @flagreturn = 0
                                              SET @RETURNSTRING='件数*每件数量+零头与数量不等，单据不能记帐'
			    close SM_Consign_CGTH
			    deallocate SM_Consign_CGTH
                                          RETURN
			END

            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)  from GOODS where  GOODSID = @GOODSID)

---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	

	IF @PRICETYPE=1   
	BEGIN
   	 SELECT @SUMAMT=@SUMAMT+ROUND(@price*@QTY*(1+ISNULL(@TAXRATE,0)*0.01),2)
	END
	IF @PRICETYPE=0  
	BEGIN
   	 SELECT @SUMAMT=@SUMAMT+ROUND(@price*@UNITQTY*(1+ISNULL(@TAXRATE,0)*0.01),2)
		IF   @QTY<>0
		BEGIN
		SET  @PRICE=(@UNITQTY*@PRICE)/@QTY
		END


	END

		SELECT @QTY=0-@QTY


                                      IF NOT (exists (select * from STORE where STOREID=@STOREID))
                                     BEGIN
			      rollback transaction trans_CGTH
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close SM_Consign_CGTH
			    deallocate SM_Consign_CGTH
                                          RETURN
			END




                                      IF exists (select * from STORE where STOREID=@STOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_CGTH
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_CGTH
			    deallocate SM_Consign_CGTH
                                          RETURN
			END



                                IF    @NEGCLOSEOFF=0 
			BEGIN 
	                             	 EXEC   GETGOODSIDEQTY  @STOREID,@GOODSID,@YYYYMM,@EQTY=@STOREIDEQTY   OUTPUT
	                                        IF  - @QTY >  ISNULL(@STOREIDEQTY,0)
             		                        BEGIN
                          		                  SET  @GOODSNAME =(SELECT NAME  FROM GOODS WHERE GOODSID=@GOODSID)
				      rollback transaction trans_CGTH
				      set @flagreturn = 0
             		                                 SET @RETURNSTRING='此'+@GOODSNAME+'库存不足不能记帐'
				    close SM_Consign_CGTH
				    deallocate SM_Consign_CGTH
	                                          RETURN
				END
			END 

            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)

	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE  ,@DetailBillFlowID, @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	    REFQTY,REFCOUNT  )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@itemNo,@GoodsID,
	     -@QTY,@price,Null,Null,@INF_COSTINGTYPEID,@UNITQTY,
	     @QTY,@price,@StoreID,'F',-1,@QTY*@PRICE,null,
	     isnull(@REFQTY,0),0 )    
	          UPDATE   STORECGTHD  set    DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_CGTH

--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

----------------------------------------
    fetch SM_Consign_CGTH into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@DetailBillFlowID,@REDetailBillFlowID,@UNITQTY,@PRICETYPE,@TAXRATE,@JianShu,@MeiJianQty,@LingTou

    END           ------- SM_Consign_CGTH  WHILE

    close SM_Consign_CGTH
    deallocate SM_Consign_CGTH

-------------------------
   	 SELECT @SUMAMT=0-@SUMAMT


-----------------------以上是解决仓库记帐问题，以下是应付帐款的问题
	IF @SFLAG=0
	BEGIN
	            IF   (not exists(select *  from VENDORBILLFLOW  where 
             		                                    (rtrim(VENDORID) = @VENDORID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
	             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,@SUMAMT,Null,
		    1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM

	END     ----------------     IF @SFLAG=0

------------------------------------2004-07-05--------------解决采购付款问题

	IF @SFLAG=1  AND  NOT( @BANKID='APSOFT')
	BEGIN
                                      IF NOT (exists (select * from BANK where BANKID=@BANKID))
                                     BEGIN
			      rollback transaction trans_CGTH
			      set @flagreturn = 0
                                              SET @RETURNSTRING='银行科目不能为空或银行科目不存在，单据不能记帐'
                                          RETURN
			END


------------------------------以下是解决科目帐的算法

	            IF   (not exists(select *  from BANKBILLFLOW  where 
             		                                    (rtrim(BANKID) = @BANKID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
	             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
			    insert into BANKBILLFLOW 
			    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
			     BAMOUNT,INAMOUNT,OUTAMOUNT,
			     INOUTFLAG,EAMOUNT   )
			    Values
			    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
			     0,0,Null,
			     @inoutFlag,0  )    
	            END      ------IF   END
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,-@SUMAMT,Null,
		     1,0  )    
	                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM

	END  ---------------	IF @SFLAG=1
-----------------------------


   update  STORECGTHM  set  flagPost = 1,YYYYMM =@BILLYYYYMM , SUMAMT= @SUMAMT ,VendorHKSum=@SUMAMT,INVOICEAMT=0         where ltrim(rtrim(BILLID)) = @BILLID 
     
   update  STORECGTHD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)          where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STORECGTHD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)   where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CGTH
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CGTH
      set @flagreturn = 0
   end
end





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_CGTH_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @REDetailBillFlowID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @BANKID   varchar(30)                     --序列号
declare @VENDORID   varchar(30)                     --序列号
declare @INF_COSTINGTYPEID   INT
declare @REFQTY   NUMERIC(20,10)
declare @QUANTITY   NUMERIC(20,10)
declare @SFLAG   INTEGER
declare @billTYPE   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间


       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BillDate =   (select BillDate  from STORECGTHM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STORECGTHM where ltrim(rtrim(BILLID)) = @BILLID ) = 0 
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CGTH_DEL   --事物开始

	SELECT @VENDORID=VENDORID    FROM STORECGTHM  where rtrim(BILLID) = @BILLID 
	SELECT @BILLTYPE=BILLTYPE    FROM STORECGTHM  where rtrim(BILLID) = @BILLID 

    declare SM_Consign_CGTH_DEL Cursor for Select GOODSID,DetailBillFlowID,STOREID,QUANTITY,REDetailBillFlowID    from STORECGTHD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CGTH_DEL

    fetch SM_Consign_CGTH_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@QUANTITY,@REDetailBillFlowID

    while @@fetch_status = 0            ----开始
    begin
                             DELETE   DetailBillFlow   WHERE  ID=@DetailBillFlowID
       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID

                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@STOREID AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
--------------------
	    fetch SM_Consign_CGTH_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@QUANTITY,@REDetailBillFlowID

    END           ------- SM_Consign_CGTH_DEL  WHILE

    close SM_Consign_CGTH_DEL
    deallocate SM_Consign_CGTH_DEL


----------------------------
                             DELETE   DetailBillFlow     WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 AND BILLTYPE=@BILLTYPE

	     set @SFLAG =   (select  ISNULL(SFLAG,0)  from  STORECGTHM where rtrim(BILLID) = @BILLID)
	     set @BANKID =   (select BANKID  from  STORECGTHM where rtrim(BILLID) = @BILLID)   ---------付款银行

		SELECT @VENDORID =(SELECT VENDORID FROM STORECGTHM    where ltrim(rtrim(BILLID)) = @BILLID )
		
		IF @SFLAG=0
		BEGIN
			DELETE   VENDORBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							AND  BILLTYPE=@BILLTYPE
             		               execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM
		END     

		IF @SFLAG=1
		BEGIN
			DELETE BANKBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
						AND  BILLTYPE=@BILLTYPE
	                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM

		END

   update  STORECGTHM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CGTH_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CGTH_DEL
      set @flagreturn = 0
   end
end






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG























----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_CKDB]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG    int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @GOODSNAME    varchar(50)               --明细存货编号
declare @STOREIDEqty NUMERIC(20,10)                          --仓库数量
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @INSTOREID varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @RATE NUMERIC(20,10)                          --数量
declare @UNITQTY NUMERIC(20,10)                          --数量
declare @REFqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @APRICE  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID  varchar(50)
declare @OUTSTOREID varchar(15)               --明细存货编号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @MINBILLDATE DATEtime
declare @MAXBILLDATE DATEtime
declare @B_ID INTEGER
declare @PRICETYPE INTEGER
declare @COUNT   INTEGER
declare @NEGCLOSEOFF   bit
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @JianShu [int] 
declare @MeiJianQty [T_QUANTITY] 
declare @LingTou [T_QUANTITY] 


       SELECT    @NEGCLOSEOFF=(SELECT  NEGCLOSEOFF  FROM   ACCINFO    WHERE   GUID='0001' )           

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
SET  @RETURNSTRING='  '

set @BILLID   = ltrim(rtrim(@BILLID))


     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @BillDate =   (select BillDate  from  STORECKDBM where rtrim(BILLID) = @BILLID)
    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END


if  (select isnull(flagPost,0) from STORECKDBM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CKDB   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STORECKDBM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STORECKDBM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STORECKDBM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STORECKDBM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  SFLAG  from STORECKDBM where rtrim(BILLID) = @BILLID)
     set @INSTOREID  =  (select  VENDORID  from STORECKDBM where rtrim(BILLID) = @BILLID)
     set @OUTSTOREID  =  (select CLIENTID  from STORECKDBM where rtrim(BILLID) = @BILLID)
           IF @INSTOREID = @OUTSTOREID
           BEGIN

	      rollback transaction trans_CKDB
	      set @flagreturn = 0
                    SET @RETURNSTRING='调出仓库和调入仓库不能为同一仓库'
                      RETURN
	END

    declare SM_Consign_CKDBOUT Cursor for Select  ITEMNO,GOODSID, isnull(QUANTITY,0) as qty,isnull(PRICE,0) as PRICE, 
                                                                   REDetailBillFlowID,Isnull(UNITQTY,0) as UNITQTY,PRICETYPE,JianShu,MeiJianQty,LingTou   from STORECKDBD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CKDBOUT

    fetch SM_Consign_CKDBOUT into @ITEMNO,@GOODSID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY ,@PRICETYPE,@JianShu,@MeiJianQty,@LingTou   

    while @@fetch_status = 0            ----开始
    begin
                     set @MeiJianQty =   (select ISNULL(RATE1,0)  from GOODS where  GOODSID = @GOODSID)


                            IF (ISNULL(@JianShu,0)*ISNULL(@MeiJianQty,0)+ISNULL(@LingTou,0)<>@Unitqty) AND (ISNULL(@JianShu,0)<>0 OR ISNULL(@LingTou,0)<>0)
                                     BEGIN
			      rollback transaction trans_CKDB
			      set @flagreturn = 0
                                              SET @RETURNSTRING='件数*每件数量+零头与数量不等，单据不能记帐'
			    close SM_Consign_CKDBOUT
			    deallocate SM_Consign_CKDBOUT
                                          RETURN
			END
                                      IF NOT (exists (select * from STORE where STOREID=@OUTSTOREID))
                                     BEGIN
			      rollback transaction trans_CKDB
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close SM_Consign_CKDBOUT
			    deallocate SM_Consign_CKDBOUT
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@OUTSTOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_CKDB
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_CKDBOUT
			    deallocate SM_Consign_CKDBOUT
                                          RETURN
			END


			declare @FuKuCunOUTQty int    ---1代表数量提示，0代表重量提示
			declare @BiJiaoQTY  NUMERIC(20,10)  ---比较过度用的变量


		        set @FuKuCunOUTQty  = (select optionvalue from accoptions where optionname ='FuKuCunOUTQty')     
		
                        IF    @NEGCLOSEOFF=0 
			BEGIN 
				IF @FuKuCunOUTQty=1
				BEGIN 
	                             	EXEC   GETGOODSIDMEQTY  @OUTSTOREID,@GOODSID,@YYYYMM,@MEQTY=@STOREIDEQTY   OUTPUT
					SET @BiJiaoQTY=@UNITQTY
				END
				ELSE
				BEGIN 
	                             	EXEC   GETGOODSIDEQTY  @OUTSTOREID,@GOODSID,@YYYYMM,@EQTY=@STOREIDEQTY   OUTPUT				
					SET @BiJiaoQTY=@QTY
				END
                                IF @BiJiaoQTY >  ISNULL(@STOREIDEQTY,0)
 		                        BEGIN
                          		                  SET  @GOODSNAME =(SELECT NAME  FROM GOODS WHERE GOODSID=@GOODSID)
				      rollback transaction trans_CKDB
				      set @flagreturn = 0
             		                                 SET @RETURNSTRING='此'+@GOODSNAME+'库存不足不能记帐'
				    close SM_Consign_CKDBOUT
				    deallocate SM_Consign_CKDBOUT
                          		                RETURN
				END
			END
            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)  from GOODS where  GOODSID = @GOODSID)


---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	



	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@OUTSTOREID ,@qty ,@PRICE ,@REDetailBillFlowID, @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output

	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT)
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     -@QTY,@price,@OUTStoreID,'F',-1,@QTY*@PRICE,null, 
	    0,0 )    
--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格


                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@OUTSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@OUTSTOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@OUTSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@OUTSTOREID,@YYYYMM
				     END

                            END




-------------------其实三种成本价的核算方式都一样  
--------反填成本单价
		IF   @SFLAG=0   --------反填
		BEGIN
			IF @PRICETYPE=1    ----吨
			BEGIN
		                      select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID
			          UPDATE   STORECKDBD  set  UNITPRICE=@APRICE
             			           WHERE CURRENT OF   SM_Consign_CKDBOUT
			END
			IF @PRICETYPE=0    ----数量
			BEGIN
		                      select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID
			          UPDATE   STORECKDBD  set  UNITPRICE=@APRICE*@QTY/@UNITQTY
             			           WHERE CURRENT OF   SM_Consign_CKDBOUT
			END
		
		END

                  
--------------------
    fetch SM_Consign_CKDBOUT into @ITEMNO,@GOODSID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY ,@PRICETYPE,@JianShu,@MeiJianQty,@LingTou   

    END           ------- SM_Consign_CKDBOUT  WHILE

    close SM_Consign_CKDBOUT
    deallocate SM_Consign_CKDBOUT


-----------------------------------------------------以上是出库，以下是入库

    declare SM_Consign_CKDBIN Cursor for Select  ITEMNO,GOODSID,isnull(QUANTITY,0) as qty,isnull(PRICE,0) as PRICE, 
                                                                   REDetailBillFlowID ,UNITQTY ,PRICETYPE   from STORECKDBD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CKDBIN

    fetch SM_Consign_CKDBIN into @ITEMNO,@GOODSID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY  ,@PRICETYPE

    while @@fetch_status = 0            ----开始
    begin
                                      IF NOT (exists (select * from STORE where STOREID=@INSTOREID))
                                     BEGIN
			      rollback transaction trans_CKDB
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close SM_Consign_CKDBIN
			    deallocate SM_Consign_CKDBIN
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@INSTOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_CKDB
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_CKDBIN
			    deallocate SM_Consign_CKDBIN
                                          RETURN
			END



            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)  from GOODS where  GOODSID = @GOODSID)


---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	


	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@INSTOREID ,@qty ,@PRICE ,@REDetailBillFlowID,  @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output

	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID, MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@INStoreID,'F',1,@QTY*@PRICE,null,
	    0,0)    

	          UPDATE   STORECKDBD  set    DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_CKDBIN
-----------====================2012-09-04 begin

	IF   @INF_COSTINGTYPEID=6 
	Begin

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output

	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID, MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,2,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@INStoreID,'F',1,@QTY*@PRICE,null,
	    0,0)    
	end
--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格

                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@INSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@INSTOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@INSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@INSTOREID,@YYYYMM
				     END

                            END



		IF   @SFLAG=0   --------反填
		BEGIN
			IF @PRICETYPE=1    ----吨
			BEGIN
		                      select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID
			          UPDATE   STORECKDBD  set  UNITPRICE=@APRICE
             			           WHERE CURRENT OF   SM_Consign_CKDBIN
			END
			IF @PRICETYPE=0    ----数量
			BEGIN
		                      select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID
			          UPDATE   STORECKDBD  set  UNITPRICE=@APRICE*@QTY/@UNITQTY
             			           WHERE CURRENT OF   SM_Consign_CKDBIN
			END
		
		END

    fetch SM_Consign_CKDBIN into @ITEMNO,@GOODSID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY  ,@PRICETYPE

    END           ------- SM_Consign_CKDBIN  WHILE

    close SM_Consign_CKDBIN
    deallocate SM_Consign_CKDBIN


   update  STORECKDBM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
   update  STORECKDBD  set   AMT  =  Round(ISNULL(quantity,0)*ISNULL(UNITprice,0),2)               where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STORECKDBD  set   AMT  =  Round(ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)            where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CKDB
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CKDB
      set @flagreturn = 0
   end
end









----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG















--------------------------------------------------------------------
----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_CKDB_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   

                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --会计年月   
DECLARE @DetailBillFlowID  varchar(8)                   --会计年月   
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @STOREID    varchar(15)               --明细存货编号
declare @REFQTY   NUMERIC(20,10)

declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)

declare @bill_type int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @INSTOREID varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @QUANTITY NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID  varchar(50)
declare @OUTSTOREID varchar(15)               --明细存货编号

declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @B_CODE VARCHAR(25)
declare @PRODUCTDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           


                                              SET @RETURNSTRING='   '


set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STORECKDBM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STORECKDBM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CKDB_DEL   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STORECKDBM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STORECKDBM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STORECKDBM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STORECKDBM where rtrim(BILLID) = @BILLID)
     set @INSTOREID  =  (select CLIENTID  from STORECKDBM where rtrim(BILLID) = @BILLID)
     set @OUTSTOREID  =  (select VENDORID  from STORECKDBM where rtrim(BILLID) = @BILLID)

    declare SM_Consign_CKDBOUT_DEL Cursor for Select  ITEMNO,GOODSID,STOREID,REDetailBillFlowID ,QUANTITY ,DetailBillFlowID   from STORECKDBD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CKDBOUT_DEL

    fetch SM_Consign_CKDBOUT_DEL into @ITEMNO,@GOODSID,@STOREID,@REDetailBillFlowID ,@QUANTITY,@DetailBillFlowID

    while @@fetch_status = 0            ----开始
    begin
	            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
             		  DELETE    DetailBillFlow    WHERE ITEMNO=@ITEMNO  AND BILLID=@BILLID  AND GOODSID=@GOODSID  AND BILLTYPE=5

                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@OUTSTOREID,@YYYYMM
	                             execute      APRICECACULATOR_STORE   @GOODSID,@INSTOREID,@YYYYMM
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@OUTSTOREID,@YYYYMM
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@INSTOREID,@YYYYMM
                            END


                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@OUTSTOREID,@YYYYMM
	                             execute      APRICECACULATOR_STORE   @GOODSID,@INSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
	                             execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@OUTSTOREID,@YYYYMM
	                             execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@INSTOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@OUTSTOREID,@YYYYMM
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@INSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
             		                execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@OUTSTOREID,@YYYYMM
             		                execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@INSTOREID,@YYYYMM
				     END

                            END


		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@OUTSTOREID  AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@INSTOREID  AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM

      fetch SM_Consign_CKDBOUT_DEL  into @ITEMNO,@GOODSID,@STOREID,@REDetailBillFlowID ,@QUANTITY,@DetailBillFlowID

    END           ------- SM_Consign_CKDBOUT  WHILE

    close SM_Consign_CKDBOUT_DEL
    deallocate SM_Consign_CKDBOUT_DEL



   update  STORECKDBM  set  flagPost = 0      where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CKDB_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CKDB_DEL
      set @flagreturn = 0
   end
end







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG
















--------------------------------------------------------------------
----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_CKPD]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @REDetailBillFlowID varchar(15)               --明细存货编号

declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)
declare @bill_type int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @RATE  NUMERIC(20,10)               --含税单价
declare @APRICE  NUMERIC(20,10)               --含税单价
declare @PRICE00  NUMERIC(20,10)               --含税单价
declare @REFQTY  NUMERIC(20,10)               --含税单价
declare @unitqty  NUMERIC(20,10)               --含税单价
declare @UNITPRICE  NUMERIC(20,10)               --含税单价
declare @MINBILLDATE DATEtime
declare @MAXBILLDATE DATEtime

declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @B_CODE VARCHAR(25)
declare @V_DATE DATEtime
declare @B_ID INTEGER
declare @COUNT INTEGER
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间


       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @BillDate =   (select BillDate  from STORECKPDM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END

if  (select isnull(flagPost,0) from STORECKPDM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CKPD   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STORECKPDM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STORECKPDM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STORECKPDM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STORECKPDM where rtrim(BILLID) = @BILLID)

    declare SM_Consign_CKPD Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(PRICE,0) as PRICE, 
                                                                   REDetailBillFlowID,ISNULL(UNITQTY,0) AS UNITQTY,ISNULL(UNITPRICE,0) AS UNITPRICE  from STORECKPDD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CKPD

    fetch SM_Consign_CKPD into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID ,@UNITQTY,@UNITPRICE

    while @@fetch_status = 0            ----开始
    begin

                                      IF NOT (exists (select * from STORE where STOREID=@STOREID))
                                     BEGIN
			      rollback transaction trans_CKPD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close SM_Consign_CKPD
			    deallocate SM_Consign_CKPD
                                          RETURN
			END

                                      IF exists (select * from STORE where STOREID=@STOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_CKPD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_CKPD
			    deallocate SM_Consign_CKPD
                                          RETURN
			END



            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)

	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE ,@REDetailBillFlowID  , @BILLID 
		IF @QTY-@price>0
		BEGIN

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output

	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID, MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT  )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY-@price,@price00,Null,Null,@INF_COSTINGTYPEID, @UNITQTY-@UNITPRICE,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     0,0 )    

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output

	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID, MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT  )
	    Values
	    (@NEWID,@BILLYYYYMM,2,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY-@price,@price00,Null,Null,@INF_COSTINGTYPEID, @UNITQTY-@UNITPRICE,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     0,0 )    

		end

		IF @QTY-@price<0
		BEGIN

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output

	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID, MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT  )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @price-@QTY,@price00,Null,Null,@INF_COSTINGTYPEID, @UNITPRICE-@UNITQTY,
	     @QTY,@price,@StoreID,'F',-1,@QTY*@PRICE,null, 
	     0,0 )    


		end




                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END


--------反填成本单价

    fetch SM_Consign_CKPD into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID ,@UNITQTY,@UNITPRICE

    END           ------- SM_Consign_CKPD  WHILE

    close SM_Consign_CKPD
    deallocate SM_Consign_CKPD
   update  STORECKPDM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CKPD
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CKPD
      set @flagreturn = 0
   end
end












----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG










----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_CKPD_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                    @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 

declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @REDetailBillFlowID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
DECLARE @INF_COSTINGTYPEID   INT
DECLARE @REFQTY   NUMERIC(20,10)
declare @QUANTITY  NUMERIC(20,10)
declare @PRICE  NUMERIC(20,10)
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STORECKPDM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STORECKPDM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CKPD_DEL   --事物开始


    declare SM_Consign_CKPD_DEL Cursor for Select GOODSID,DetailBillFlowID,STOREID,QUANTITY,PRICE,REDetailBillFlowID    from STORECKPDD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CKPD_DEL

    fetch SM_Consign_CKPD_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@QUANTITY,@PRICE,@REDetailBillFlowID

    while @@fetch_status = 0            ----开始
    begin
                             DELETE   DetailBillFlow   WHERE  ID=@DetailBillFlowID
       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID

                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

--------------------
		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@STOREID AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
      fetch SM_Consign_CKPD_DEL into  @GOODSID,@DetailBillFlowID,@STOREID,@QUANTITY,@PRICE,@REDetailBillFlowID

    END           ------- SM_Consign_CKPD_DEL  WHILE

    close SM_Consign_CKPD_DEL
    deallocate SM_Consign_CKPD_DEL

                            DELETE   DetailBillFlow     WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND (YYYYMMBILL in (1,2)) AND BILLTYPE=6

   update  STORECKPDM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CKPD_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CKPD_DEL
      set @flagreturn = 0
   end
end







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG

















----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_CSH]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ITEMNO varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @RATE NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @UNITQTY  NUMERIC(20,10)               --含税单价
declare @SUMAMT  NUMERIC(20,10)               --含税单价
declare @TAXRATE NUMERIC(20,10)                          --单据总金额

declare @BILLTYPE INTEGER
declare @PRICETYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @STOREHSFS   INTEGER
declare @JianShu [int] 
declare @MeiJianQty [T_QUANTITY] 
declare @LingTou [T_QUANTITY] 

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

if  (select isnull(flagPost,0) from STORECSHM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CSH   --事物开始

--     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')      
     set @YYYYMM   = '199912'
 
     set @INOUTFLAG =   (select INOUTFLAG from STORECSHM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STORECSHM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STORECSHM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STORECSHM where rtrim(BILLID) = @BILLID)
   	 SELECT @SUMAMT=0


    declare SM_Consign_CSH Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(UNITPRICE,0) as PRICE,
                                                                  PRICETYPE,ISNULL(UNITQTY,0)   AS UNITQTY,JianShu,MeiJianQty,LingTou   from STORECSHD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CSH

    fetch SM_Consign_CSH into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@PRICETYPE,@UNITQTY,@JianShu,@MeiJianQty,@LingTou

    while @@fetch_status = 0            ----开始
    begin
                     set @MeiJianQty =   (select ISNULL(RATE1,0)  from GOODS where  GOODSID = @GOODSID)


                            IF (ISNULL(@JianShu,0)*ISNULL(@MeiJianQty,0)+ISNULL(@LingTou,0)<>@Unitqty) AND (ISNULL(@JianShu,0)<>0 OR ISNULL(@LingTou,0)<>0)
                                     BEGIN
			      rollback transaction trans_CSH
			      set @flagreturn = 0
                                              SET @RETURNSTRING='件数*每件数量+零头与数量不等，单据不能记帐'
			    close SM_Consign_CSH
			    deallocate SM_Consign_CSH
                                          RETURN
			END



            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)



---------------根据理算系数核算重量与数量
            set @RATE =   (select ISNULL(RATE,0)  from GOODS where  GOODSID = @GOODSID)

---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	

	IF @PRICETYPE=0  
	BEGIN
		IF   @QTY<>0
		BEGIN
		SET  @PRICE=(@UNITQTY*@PRICE)/@QTY
		END

	END





                                        IF NOT (exists (select * from STORE where STOREID=@STOREID))
                                     BEGIN
			      rollback transaction trans_CSH
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close SM_Consign_CSH
			    deallocate SM_Consign_CSH
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@STOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_CSH
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_CSH
			    deallocate SM_Consign_CSH
                                          RETURN
			END



	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE ,@DetailBillFlowID  , @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID, 
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT ,MINQTY)
	    Values
	    (@NEWID,@YYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID,
	     @QTY,@price,@StoreID,'F',@inoutFlag,@QTY*@PRICE,null,
	     0,0  ,@UNITQTY)    
	          UPDATE   STORECSHD  set    DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_CSH



-----------====================2012-09-04 begin

	IF   @INF_COSTINGTYPEID=6 
	Begin

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID, 
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT ,MINQTY)
	    Values
	    (@NEWID,@YYYYMM,2,@BillDate,@BillType,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID,
	     @QTY,@price,@StoreID,'F',@inoutFlag,@QTY*@PRICE,null,
	     0,0  ,@UNITQTY)    
	END

--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

--------------------
    fetch SM_Consign_CSH into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@PRICETYPE,@UNITQTY,@JianShu,@MeiJianQty,@LingTou

    END           ------- SM_Consign_CSH  WHILE

    close SM_Consign_CSH
    deallocate SM_Consign_CSH
   update  STORECSHM  set  flagPost = 1,YYYYMM =@YYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CSH
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CSH
      set @flagreturn = 0
   end
end













----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_CSH_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 

declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @STOREHSFS   INTEGER

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @YYYYMMBILL =   (select YYYYMM  from STORECSHM where rtrim(BILLID) = @BILLID)
       IF   @YYYYMM<>  @YYYYMMBILL
       BEGIN
       SET @RETURNSTRING=' 帐套启用后，仓库初始化单据不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  ((select isnull(flagPost,0) from STORECSHM where ltrim(rtrim(BILLID)) = @BILLID ) = 0) or (not (@YYYYMM=@YYYYMMBILL))
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CSH_DEL   --事物开始

     DELETE   DetailBillFlow 
     UPDATE  GOODS  SET APRICE=0
     DELETE   GOODSINIT

   update  STORECSHM  set  flagPost = 0    --------where ltrim(rtrim(BILLID)) = @BILLID 
     
     -------------仓库初始化单据取消记帐是全部取消记帐
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CSH_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CSH_DEL
      set @flagreturn = 0
   end
end




----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG



















CREATE PROCEDURE [dbo].[STORE_CW_PingZheng]  
                 (
                  @BILLID varchar(22),      ---单据编号  
                  @BILLPost varchar(20),      ---单据编号  
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @Detailflag int                     --业务类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @Debit NUMERIC(20,2)
declare @ItemBM  varchar(50)               --明细存货编号
declare @NewItemBM varchar(20)               --明细存货编号
declare @PrevNO varchar(20)               --明细存货编号
declare @CredCode   varchar(20)               --明细存货编号
declare @CredTypeName   varchar(20)               --明细存货编号
declare @DuiFangKeMu   varchar(30)               --明细存货编号
declare @CredTypeID   int
declare @credit NUMERIC(20,2)
declare @BILLCODE VARCHAR(25)
declare @Brief VARCHAR(200)
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER


SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

     set @BillDate =   (select BillDate  from CW_PingZhengM where rtrim(BILLID) = @BILLID)
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='CW_YYYYMM')     


if  (select isnull(flagPost,0) from CW_PingZhengM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CW_PingZheng   --事物开始

--     set @BillCode =   (select CODE from CW_PingZhengM where rtrim(BILLID) = @BILLID)
     set @Credcode =   (select Credcode from CW_PingZhengM where rtrim(BILLID) = @BILLID)
     set @CredTypeID =   (select CredTypeID from CW_PingZhengM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from CW_PingZhengM where rtrim(BILLID) = @BILLID)

    select  @CredTypeName=Name from CredType where CredTypeID=@CredTypeID

	set  @BillCode=@CredTypeName+@Credcode

    declare SM_Consign_CW_PingZheng Cursor for Select  ITEMNO,ItemBM,Debit, credit,Brief   from CW_PingZhengD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CW_PingZheng

    fetch SM_Consign_CW_PingZheng into @ITEMNO,@ItemBM,@Debit,@credit,@Brief

    while @@fetch_status = 0            ----开始
    begin

-------缺少检测仓库  明日解决
----(itembm not in (select prevno from iteminfo) 

                      IF NOT (exists (select * from iteminfo where Detailflag=1 and ItemBM = @ItemBM))
                       BEGIN
			      set @flagreturn = 0
                             SET @RETURNSTRING='科目不存在或为空或为非明细科目，单据不能记帐'
			    close SM_Consign_CW_PingZheng
			    deallocate SM_Consign_CW_PingZheng
			      rollback transaction trans_CW_PingZheng

                            RETURN
			END
--------------------判断现金银行日记账

--------------------固化会计科目编码第一级为4位		    

			set @DuiFangKeMu=' '

		    if  substring(@ItemBM,1,4)='1001'  or substring(@ItemBM,1,4)='1002'
			begin

			select @DuiFangKeMu=ItemBM from CW_PingZhengD  where rtrim(BILLID) = @BILLID  and   ItemBM<>@ItemBM  and (Debit=@credit OR  credit=@Debit )

			end


--------------------

		    set @NewItemBM=@ItemBM
			
		    select @PrevNO='9999AAAA'

		
	      while  (@PrevNO<>'0000') 
	      begin
	        select @Detailflag=Detailflag from ItemInfo where ItemBM=@NewItemBM


			    EXEC  CW_BillFlow_insert_YYYYMM  @NewItemBM
	
		            execute  GETKEYVALUE     'CW_BillFlow',@R_KeyValue = @NEWID output
			    insert into CW_BillFlow 
			    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLID,BILLCODE,ITEMNO,ItemBM,
			     Debit,credit,Brief,Detailflag,duifangKemu  )
			    Values
			    (@NEWID,@YYYYMM,1,@BillDate,@BillID,@BillCode,@itemNo,@NewItemBM,
			     @Debit,@credit,@Brief,@Detailflag,@duifangKemu )    

		             execute   CW_CACULATOR_YYYYMM @NewItemBM,@YYYYMM

	        select @PrevNO=PrevNO from ItemInfo where ItemBM=@NewItemBM


		SET @NewItemBM=@PrevNO

	     end          -------while  @PrevNO<>'0000' 



--------------------
    fetch SM_Consign_CW_PingZheng into @ITEMNO,@ItemBM,@Debit,@credit,@Brief

    END           ------- SM_Consign_CW_PingZheng  WHILE

    close SM_Consign_CW_PingZheng
    deallocate SM_Consign_CW_PingZheng

   update  CW_PingZhengM  set  flagPost = 1,BILLPost=@BillPost         where ltrim(rtrim(BILLID)) = @BILLID 
    

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CW_PingZheng
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CW_PingZheng
      set @flagreturn = 0
   end
end











----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[STORE_CW_PingZheng_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @ItemBM varchar(20)               --明细存货编号
declare @NewItemBM varchar(20)               --明细存货编号
declare @PrevNO varchar(20)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @Debit    varchar(15)               --明细存货编号
declare @credit   varchar(30)                     --序列号
declare @VENDORID   varchar(30)                     --序列号
declare @Detailflag   INT
declare @VENDORFLAG   INT
declare @SFLAG   INT
declare @REFQTY   NUMERIC(20,10)
declare @STOREHSFS   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER

                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='CW_YYYYMM')       
     set @BILLDate =  (select BILLDate  from CW_PingZhengM where rtrim(BILLID) = @BILLID)

if  (select isnull(flagPost,0) from CW_PingZhengM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CW_PingZheng_DEL   --事物开始

     DELETE   CW_BILLFLOW     WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 

    declare SM_Consign_CW_PingZheng_DEL Cursor for Select ItemBM,credit,Debit,BILLID    from CW_PingZhengD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CW_PingZheng_DEL

    fetch SM_Consign_CW_PingZheng_DEL into @ItemBM,@credit,@Debit,@BILLID

    while @@fetch_status = 0            ----开始
    begin

		    set @NewItemBM=@ItemBM
			
		    select @PrevNO='9999AAAA'

		
	      while  (@PrevNO<>'0000') 
	      begin
	        select @Detailflag=Detailflag from ItemInfo where ItemBM=@NewItemBM

		      execute   CW_CACULATOR_YYYYMM @NewItemBM,@YYYYMM
	
	        select @PrevNO=PrevNO from ItemInfo where ItemBM=@NewItemBM


		SET @NewItemBM=@PrevNO

	     end          -------while  @PrevNO<>'0000' 



    fetch SM_Consign_CW_PingZheng_DEL into @ItemBM,@credit,@Debit,@BILLID

    END           ------- SM_Consign_CW_PingZheng_DEL  WHILE

    close SM_Consign_CW_PingZheng_DEL
    deallocate SM_Consign_CW_PingZheng_DEL


   update  CW_PingZhengM  set  flagPost = 0 ,BILLPost=NULL   where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CW_PingZheng_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CW_PingZheng_DEL
      set @flagreturn = 0
   end
end







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_Calculate_Aprice]  
                 (
                              @Curr_YYYYMM   varchar(20),   --传入当前会计期间
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @BILLID  varchar(10)                   --会计年月     
declare @SFLAG  INT
declare @PRICETYPE  INT

declare @APRICE  NUMERIC(20,10) 
declare @QTY  NUMERIC(20,10) 
declare @unitQTY  NUMERIC(20,10) 

--           WAITFOR   DELAY   '0:00:10'

     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_Calculate_Aprice   --事物开始


    declare SM_Calculate_Aprice Cursor for Select DetailBillFlowID    from STOREXSCKD where BILLID in (select BILLID  from STOREXSCKM   where  YYYYMM=@Curr_YYYYMM) 

    Open SM_Calculate_Aprice

    fetch SM_Calculate_Aprice into    @DetailBillFlowID

    while @@fetch_status = 0            ----开始
    begin
	                 SELECT  @APRICE =INPRICE    FROM DETAILBILLFLOW  
             		               WHERE ID= @DETAILBILLFLOWID
                              if  @APRICE is null
                              begin
                                      set @APRICE=0.00
		   end
               UPDATE   STOREXSCKD  set    APRICE=@APRICE    WHERE CURRENT OF  SM_Calculate_Aprice

--------------------
      fetch SM_Calculate_Aprice   into @DetailBillFlowID      

    END           ------- SM_Calculate_Aprice  WHILE

    close SM_Calculate_Aprice
    deallocate SM_Calculate_Aprice
    
-------------------------------------------------------============
    declare SM_Calculate_Aprice Cursor for Select DetailBillFlowID    from STOREXSTHD where BILLID in (select BILLID  from STOREXSTHM   where  YYYYMM=@Curr_YYYYMM) 

    Open SM_Calculate_Aprice

    fetch SM_Calculate_Aprice into    @DetailBillFlowID

    while @@fetch_status = 0            ----开始
    begin
	                 SELECT  @APRICE =INPRICE    FROM DETAILBILLFLOW  
             		               WHERE ID= @DETAILBILLFLOWID
                              if  @APRICE is null
                              begin
                                      set @APRICE=0.00
		   end
               UPDATE   STOREXSTHD  set    APRICE=@APRICE    WHERE CURRENT OF  SM_Calculate_Aprice

--------------------
      fetch SM_Calculate_Aprice   into @DetailBillFlowID      

    END           ------- SM_Calculate_Aprice  WHILE

    close SM_Calculate_Aprice
    deallocate SM_Calculate_Aprice
    
-------------------------------------------------------============销售出库单和销售退货单反填“吨”价格
    declare SM_Calculate_Aprice Cursor for Select DetailBillFlowID,BILLID,PRICETYPE,quantity,unitqty    from STOREQTCKD where BILLID in (select BILLID  from STOREQTCKM   where  YYYYMM=@Curr_YYYYMM) 

    Open SM_Calculate_Aprice

    fetch SM_Calculate_Aprice into    @DetailBillFlowID,@BILLID,@PRICETYPE,@qty,@unitqty

    while @@fetch_status = 0            ----开始
    begin
	                 SELECT  @APRICE =INPRICE    FROM DETAILBILLFLOW  
             		               WHERE ID= @DETAILBILLFLOWID
                              if  @APRICE is null
                              begin
                                      set @APRICE=0.00
		   end
		select @SFLAG=(SELECT SFLAG  FROM STOREQTCKM  WHERE  BILLID=@BILLID)
		IF   @SFLAG=0   --------反填
		BEGIN
	                   	   select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@DetailBillFlowID
			IF @PRICETYPE=1    ----吨
			BEGIN
			          UPDATE     STOREQTCKD     set    APRICE=@APRICE,UNITPRICE=@APRICE
             		    	    	   WHERE CURRENT OF SM_Calculate_Aprice
			END

			IF @PRICETYPE=0    ----数量
			BEGIN
			          UPDATE     STOREQTCKD     set    APRICE=@APRICE,UNITPRICE=@APRICE*@QTY/@UNITQTY
             		    	    	   WHERE CURRENT OF SM_Calculate_Aprice
			END

		END

               UPDATE   STOREQTCKD  set    APRICE=@APRICE    WHERE CURRENT OF  SM_Calculate_Aprice

--------------------
    fetch SM_Calculate_Aprice into    @DetailBillFlowID,@BILLID,@PRICETYPE,@qty,@unitqty

    END           ------- SM_Calculate_Aprice  WHILE

    close SM_Calculate_Aprice
    deallocate SM_Calculate_Aprice
    
-------------------------------------------------------============
-------------------------------------------------------============
    declare SM_Calculate_Aprice Cursor for Select DetailBillFlowID,BILLID,PRICETYPE,quantity,unitqty    from STORECKDBD where BILLID in (select BILLID  from STORECKDBM   where  YYYYMM=@Curr_YYYYMM) 

    Open SM_Calculate_Aprice

    fetch SM_Calculate_Aprice into    @DetailBillFlowID,@BILLID,@PRICETYPE,@qty,@unitqty

    while @@fetch_status = 0            ----开始
    begin
	                 SELECT  @APRICE =INPRICE    FROM DETAILBILLFLOW  
             		               WHERE ID= @DETAILBILLFLOWID
                              if  @APRICE is null
                              begin
                                      set @APRICE=0.00
		   end
		select @SFLAG=(SELECT SFLAG  FROM STORECKDBM  WHERE  BILLID=@BILLID)
		IF   @SFLAG=0   --------反填
		BEGIN
	                   	   select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@DetailBillFlowID
			IF @PRICETYPE=1    ----吨
			BEGIN
			          UPDATE     STORECKDBD     set    APRICE=@APRICE,UNITPRICE=@APRICE
             		    	    	   WHERE CURRENT OF SM_Calculate_Aprice
			END

			IF @PRICETYPE=0    ----数量
			BEGIN
			          UPDATE     STORECKDBD     set    APRICE=@APRICE,UNITPRICE=@APRICE*@QTY/@UNITQTY
             		    	    	   WHERE CURRENT OF SM_Calculate_Aprice
			END

		END

               UPDATE   STORECKDBD  set    APRICE=@APRICE    WHERE CURRENT OF  SM_Calculate_Aprice

--------------------
    fetch SM_Calculate_Aprice into    @DetailBillFlowID,@BILLID,@PRICETYPE,@qty,@unitqty

    END           ------- SM_Calculate_Aprice  WHILE

    close SM_Calculate_Aprice
    deallocate SM_Calculate_Aprice
    
-------------------------------------------------------============
-------------------------------------------------------============


   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_Calculate_Aprice
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_Calculate_Aprice
      set @flagreturn = 0
   end




----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














--------------------------------------------------------------------

CREATE PROCEDURE [STORE_FYKZ]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。


declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)

declare @bill_type int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @CLIENTID   varchar(15)               --明细存货编号
declare @VendorID   varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @SUMAMT NUMERIC(20,10)                          --数量
declare @refqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @INBANKID VARCHAR(25)
declare @BILLDATE DATEtime
declare @MINBILLDATE DATEtime
declare @MAXBILLDATE DATEtime
declare @B_CODE VARCHAR(25)
declare @V_DATE DATEtime
declare @ClientFlag int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @B_ID INTEGER
declare @STOREHSFS   INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @YYYYMM_FLAG  INTEGER

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

   declare  @PREV_YYYYMM          varchar(6)  -- 上一个会计年月
   declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     

     set @BillDate =   (select BillDate  from STOREFYKZM where rtrim(BILLID) = @BILLID)
    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END



if  (select isnull(flagPost,0) from STOREFYKZM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_FYKZ   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREFYKZM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREFYKZM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREFYKZM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREFYKZM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  SFLAG  from STOREFYKZM where rtrim(BILLID) = @BILLID)
     set @INBANKID =   (select  VENDORID  from STOREFYKZM where rtrim(BILLID) = @BILLID)
     set @ClientFLAG =   (select  ISNULL(ClientFLAG,1)   from STOREFYKZM where rtrim(BILLID) = @BILLID)
     set @CLIENTID =   (select CLIENTID  from STOREFYKZM where rtrim(BILLID) = @BILLID)



                                      IF NOT (exists (select * from BANK where BANKID=@INBANKID))
                                     BEGIN
			      rollback transaction trans_FYKZ
			      set @flagreturn = 0
                                              SET @RETURNSTRING='银行科目不能为空或银行科目不存在，单据不能记帐'
                                          RETURN
			END
   	 SELECT @SUMAMT= (SELECT SUM(QUANTITY)  FROM  STOREFYKZD   where rtrim(BILLID) = @BILLID)

------------------------------以下是解决科目帐的算法
            IF   (not exists(select *  from BANKBILLFLOW  where 
             		                                    (rtrim(BANKID) = @INBANKID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@INBANKID,
		     0,0,Null,
		     @inoutFlag,0  )    
            END      ------IF   END
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@INBANKID,
		     0,@SUMAMT,Null,
		     -1,0  )    
                            execute      BANK_CACULATOR_YYYYMM   @INBANKID,@YYYYMM
------------------------------------



	IF  @ClientFLAG=1  and @CLIENTID<>''
	BEGIN
	            IF   (not exists(select *  from CLIENTBILLFLOW  where 
             		                                    (rtrim(CLIENTID) = @CLIENTID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE, CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode, @CLIENTID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE, CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode, @CLIENTID,
		     0,@SUMAMT,Null,
		     1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM
	END         ---------------IF @SFLAG=0



	IF  @ClientFLAG=0  and @CLIENTID<>''
	BEGIN

	      SET @VendorID=@ClientID
	            IF   (not exists(select *  from VENDORBILLFLOW  where 
             		                                    (rtrim(VENDORID) = @VENDORID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
	             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,-@SUMAMT,Null,
		     1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM

	END     ----------------     IF @SFLAG=0







------------------------------------

   update  STOREFYKZM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_FYKZ
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_FYKZ
      set @flagreturn = 0
   end
end






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_FYKZ_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 

declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @BANKID    varchar(15)               --明细存货编号
declare @INBANKID    varchar(15)               --明细存货编号
declare @CLIENTID   varchar(30)                     --序列号
declare @VendorID   varchar(30)                     --序列号
declare @INF_COSTINGTYPEID   INT
declare @REFQTY   NUMERIC(20,10)
declare @ClientFlag int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STOREFYKZM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREFYKZM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_FYKZ_DEL   --事物开始


	     set @INBANKID =   (select  VENDORID  from STOREFYKZM where rtrim(BILLID) = @BILLID)

     set @ClientFLAG =   (select  ISNULL(ClientFLAG,1)   from STOREFYKZM where rtrim(BILLID) = @BILLID)
     set @CLIENTID =   (select CLIENTID  from STOREFYKZM where rtrim(BILLID) = @BILLID)

		DELETE   BANKBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=13
                            execute      BANK_CACULATOR_YYYYMM   @INBANKID,@YYYYMM


	IF      @ClientFlag=1
	BEGIN
		DELETE   CLIENTBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=13
                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM
	END

		IF  @ClientFlag=0
		BEGIN

		      SET @VendorID=@ClientID
			DELETE   VENDORBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=13
             		               execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM
	                             DELETE  VENDORBILLFLOW    WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 AND BILLTYPE=13
--------------------------------------以上上全部删除单据  是解决多次记帐失败的问题

		END     



   update  STOREFYKZM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_FYKZ_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_FYKZ_DEL
      set @flagreturn = 0
   end
end






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG
















--------------------------------------------------------------------

CREATE PROCEDURE [STORE_GJRK]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---是否现款标志
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @VENDORID   varchar(15)               --明细存货编号
declare @bankID   varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @RATE NUMERIC(20,10)                          --单据总金额

declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @SUMAMT NUMERIC(20,10)                          --单据总金额
declare @refqty NUMERIC(20,10)                          --引用数量
declare @UNITQTY NUMERIC(20,10)                          --引用数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @lcode varchar(30)                     --序列号
declare @REDetailBillFlowID varchar(30)                     --序列号
declare @BILLTYPE INTEGER
declare @status INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @JianShu [int] 
declare @MeiJianQty [T_QUANTITY] 
declare @LingTou [T_QUANTITY] 


       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

     set @BillDate =   (select BillDate  from STOREGJRKM where rtrim(BILLID) = @BILLID)
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     

    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END

if  (select isnull(flagPost,0) from STOREGJRKM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_GJRK   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREGJRKM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREGJRKM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREGJRKM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREGJRKM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREGJRKM where rtrim(BILLID) = @BILLID)
     set @VENDORID =   (select  VENDORID  from STOREGJRKM where rtrim(BILLID) = @BILLID)
     set @BANKID =   (select BANKID  from STOREGJRKM where rtrim(BILLID) = @BILLID)   ---------付款银行
	     set @STATUS =   (select STATUS  from STOREGJRKM where rtrim(BILLID) = @BILLID)

                                      IF NOT (exists (select * from VENDOR where VENDORID=@VENDORID))
                                     BEGIN
			      rollback transaction trans_GJRK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='供应商不能为空或供应商不存在，单据不能记帐'
                                          RETURN
			END

   	 SELECT @SUMAMT= (SELECT SUM(ROUND(unitprice*QUANTITY,2)) FROM   STOREGJRKD  where rtrim(BILLID) = @BILLID)


    declare SM_Consign_GJRK Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(unitPRICE,0)    as PRICE, 
                                                                 DetailBillFlowID,REDetailBillFlowID,isnull(UNITQTY,0) AS UNITQTY,JianShu,MeiJianQty,LingTou    from STOREGJRKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_GJRK

    fetch SM_Consign_GJRK into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE, @DetailBillFlowID,@REDetailBillFlowID,@UNITQTY,@JianShu,@MeiJianQty,@LingTou

    while @@fetch_status = 0            ----开始
    begin

-------缺少检测仓库  明日解决
                            IF (ISNULL(@JianShu,0)*ISNULL(@MeiJianQty,0)+ISNULL(@LingTou,0)<>@Unitqty) AND (ISNULL(@JianShu,0)<>0 OR ISNULL(@MeiJianQty,0)<>0 OR ISNULL(@LingTou,0)<>0)
                                     BEGIN
			      rollback transaction trans_GJRK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='件数*每件数量+零头与数量不等，单据不能记帐'
			    close SM_Consign_GJRK
			    deallocate SM_Consign_GJRK
                                          RETURN
			END


                                      IF NOT (exists (select * from STORE where STOREID=@STOREID))
                                     BEGIN
			      rollback transaction trans_GJRK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close SM_Consign_GJRK
			    deallocate SM_Consign_GJRK
                                          RETURN
			END

            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)  from GOODS where  GOODSID = @GOODSID)


---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	




	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE  ,@DetailBillFlowID,  @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID, MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT  )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     isnull(@REFQTY,0),0 )    
	          UPDATE   STOREGJRKD  set    DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_GJRK


-----------====================2012-09-04 begin

	IF   @INF_COSTINGTYPEID=6 
	Begin

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID, MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT  )
	    Values
	    (@NEWID,@BILLYYYYMM,2,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     isnull(@REFQTY,0),0 )    

-----///===	update DetailBillFlow  where ID=@NEWID
	END

--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END


--------------------
    fetch SM_Consign_GJRK into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE, @DetailBillFlowID,@REDetailBillFlowID,@UNITQTY,@JianShu,@MeiJianQty,@LingTou

    END           ------- SM_Consign_GJRK  WHILE

    close SM_Consign_GJRK
    deallocate SM_Consign_GJRK

-----------------------以上是解决仓库记帐问题，以下是应付帐款的问题

----------------------判断是否存在在估入库供应商，如果没有则系统自动建立
 
		   if not exists (select  * FROM VENDOR  WHERE VENDORID='AAAAAAAA')
		  BEGIN

			select  @lcode= max(lcode)  from area
			INSERT INTO   VENDOR  (VENDORID,CODE,NAME,areaid)
			    Values   ('AAAAAAAA','ZGRKCODE','在估入库',@lcode)

		  END

		select  @vendorid='AAAAAAAA'

	            IF   (not exists(select *  from VENDORBILLFLOW  where 
             		                                    (rtrim(VENDORID) = @VENDORID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
	             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,@SUMAMT,Null,
		     1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM


-----------------------------
   update  STOREGJRKM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_GJRK
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_GJRK
      set @flagreturn = 0
   end
end












----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_GJRK_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @REBILLID    varchar(15)               --明细存货编号
declare @VENDORID   varchar(30)                     --序列号
declare @billtype   INT
declare @STATUS   INT
declare @SFLAG   INT
declare @INF_COSTINGTYPEID  INT                ---本期期初加权价
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BillDate =   (select BillDate  from STOREGJRKM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREGJRKM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_GJRK_DEL   --事物开始

	SELECT @VENDORID=VENDORID    FROM STOREGJRKM  where rtrim(BILLID) = @BILLID 
	     set @BillType =   (select BillType  from STOREGJRKM where rtrim(BILLID) = @BILLID)
	     set @STATUS =   (select STATUS  from STOREGJRKM where rtrim(BILLID) = @BILLID)
	     set @REBILLID=   (select REFERBILLCODE  from STOREGJRKM where rtrim(BILLID) = @BILLID)


			IF exists(select   ITEMNO   FROM    STOREGJRKD  where rtrim(BILLID) = @BILLID  AND  ITEMNO  IN (SELECT  REGJRKITEMNO   FROM    STORECGRKD ))
			BEGIN
                                              SET @RETURNSTRING=' 此估价入库单已经被采购入库单引用不能取消记帐  '
			      rollback transaction trans_GJRK_DEL
			      set @flagreturn = 0
                                         RETURN
			END

			IF @STATUS=1
			BEGIN
                                              SET @RETURNSTRING=' 此估价入库单是由被采购入库单生成不能取消记帐  '
			      rollback transaction  trans_GJRK_DEL
			      set @flagreturn = 0
                                         RETURN
			END


    declare SM_Consign_GJRK_DEL Cursor for Select GOODSID,DetailBillFlowID,STOREID,BILLID    from STOREGJRKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_GJRK_DEL

    fetch SM_Consign_GJRK_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@BILLID

    while @@fetch_status = 0            ----开始
    begin

                             DELETE   DetailBillFlow     WHERE  ID=@DetailBillFlowID
--------------------------------------以上是删除一条单据明细
       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@STOREID AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
    fetch SM_Consign_GJRK_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@BILLID

    END           ------- SM_Consign_GJRK_DEL  WHILE

    close SM_Consign_GJRK_DEL
    deallocate SM_Consign_GJRK_DEL

                             DELETE   DetailBillFlow     WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND (YYYYMMBILL in (1,2)) AND BILLTYPE=@billtype
--------------------------------------以上上全部删除单据  是解决多次记帐失败的问题

----------------------------
	     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREGJRKM where rtrim(BILLID) = @BILLID)
	     set @BANKID =   (select BANKID  from STOREGJRKM where rtrim(BILLID) = @BILLID)   ---------付款银行

		SELECT @VENDORID ='AAAAAAAA'
		
			DELETE   VENDORBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@BILLTYPE
             		               execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM
	                             DELETE  VENDORBILLFLOW    WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 AND BILLTYPE=@billtype



   update  STOREGJRKM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_GJRK_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_GJRK_DEL
      set @flagreturn = 0
   end
end







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG








-------------------------此过程除了--------------删除单据
CREATE PROCEDURE [STORE_GJRK_DEL_CGRK]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @REBILLID    varchar(15)               --明细存货编号
declare @VENDORID   varchar(30)                     --序列号
declare @billtype   INT
declare @STATUS   INT
declare @SFLAG   INT
declare @REFQTY   NUMERIC(20,10)

set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       

     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_GJRK_DEL_CGRK  --事物开始

	     set @BillType =   (select BillType  from STOREGJRKM where rtrim(BILLID) = @BILLID)

                   DELETE   DetailBillFlow     WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 AND BILLTYPE=@billtype

	     set @BANKID =   (select BANKID  from STOREGJRKM where rtrim(BILLID) = @BILLID)   ---------付款银行

		              SELECT @VENDORID ='AAAAAAAA'
		
			DELETE   VENDORBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@BILLTYPE
             		               execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM

	  DELETE   STOREGJRKM      where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_GJRK_DEL_CGRK
      set @flagreturn = 1
   end
   else
   begin
      rollback transaction trans_GJRK_DEL_CGRK
      set @flagreturn = 0
   end




----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG









CREATE PROCEDURE [STORE_INVOICE]  
                 (
                  @BILLID varchar(22)      ---单据编号   
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @REFERBILLTYPE int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @VENDORFLAG  int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @VENDORID varchar(15)               --明细存货编号
declare @REFERBILLID varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @REFERBILLITEMNO varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @INVOICENOW  NUMERIC(20,10)               --含税单价
declare @QUANTITY  NUMERIC(20,10)               --含税单价
declare @BATCHCODE varchar(30)                     --序列号
declare @BILLKIND  INTEGER
declare @INVOICETYPE  INTEGER
--//declare @BILLKIN D INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @STOREHSFS   INTEGER

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
set @BILLID   = ltrim(rtrim(@BILLID))

		SELECT @BILLKIND=BILLKIND FROM     INVOICEM   where rtrim(BILLID) = @BILLID 
		SELECT @INVOICETYPE=INVOICETYPE FROM     INVOICEM   where rtrim(BILLID) = @BILLID 
    declare SM_Consign_INVOICE Cursor for Select  REFERBILLID,INVOICENOW,ITEMNO,REFERBILLTYPE   from INVOICED   where rtrim(BILLID) = @BILLID 

    Open SM_Consign_INVOICE

    fetch SM_Consign_INVOICE into @REFERBILLID,@INVOICENOW,@ITEMNO,@REFERBILLTYPE

    while @@fetch_status = 0            ----开始
    begin
	           IF  @REFERBILLTYPE=1
		BEGIN
		          UPDATE   STORECGRKM  set    INVOICEAMT=ISNULL(INVOICEAMT,0) +@INVOICENOW,INVOICETYPE=@INVOICETYPE
             		           WHERE  rtrim(BILLID) = @REFERBILLID
		END

	           IF  @REFERBILLTYPE=2 
		BEGIN
		          UPDATE   STOREXSCKM  set    INVOICEAMT=ISNULL(INVOICEAMT,0) +@INVOICENOW,INVOICETYPE=@INVOICETYPE
             		           WHERE  rtrim(BILLID) = @REFERBILLID
		END



	           IF  @REFERBILLTYPE=7
		BEGIN
		          UPDATE   STORECGTHM  set    INVOICEAMT=ISNULL(INVOICEAMT,0) +@INVOICENOW,INVOICETYPE=@INVOICETYPE
             		           WHERE  rtrim(BILLID) = @REFERBILLID
		END

	           IF  @REFERBILLTYPE=12 
		BEGIN
		          UPDATE   STOREXSTHM  set    INVOICEAMT=ISNULL(INVOICEAMT,0) +@INVOICENOW,INVOICETYPE=@INVOICETYPE
             		           WHERE  rtrim(BILLID) = @REFERBILLID
		END



    fetch SM_Consign_INVOICE into @REFERBILLID,@INVOICENOW,@ITEMNO,@REFERBILLTYPE

    END           ------- SM_Consign_INVOICE  WHILE

    close SM_Consign_INVOICE
    deallocate SM_Consign_INVOICE






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG









CREATE PROCEDURE [STORE_INVOICE_DEL]  
                 (
                  @BILLID varchar(22)      ---单据编号   
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @REFERBILLTYPE int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @VENDORFLAG  int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @VENDORID varchar(15)               --明细存货编号
declare @REFERBILLID varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @REFERBILLITEMNO varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @INVOICENOW  NUMERIC(20,10)               --含税单价
declare @QUANTITY  NUMERIC(20,10)               --含税单价
declare @BATCHCODE varchar(30)                     --序列号
declare @BILLKIND  INTEGER
--//declare @BILLKIN D INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @STOREHSFS   INTEGER

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
set @BILLID   = ltrim(rtrim(@BILLID))

		SELECT @BILLKIND=BILLKIND FROM     INVOICEM   where rtrim(BILLID) = @BILLID 
    declare SM_Consign_INVOICE_DEL Cursor for Select  REFERBILLID,INVOICENOW,ITEMNO,REFERBILLTYPE   from INVOICED   where rtrim(BILLID) = @BILLID 

    Open SM_Consign_INVOICE_DEL

    fetch SM_Consign_INVOICE_DEL into @REFERBILLID,@INVOICENOW,@ITEMNO,@REFERBILLTYPE

    while @@fetch_status = 0            ----开始
    begin
	           IF  @REFERBILLTYPE=1 
		BEGIN
		          UPDATE   STORECGRKM  set    INVOICEAMT=ISNULL(INVOICEAMT,0) -@INVOICENOW
             		           WHERE  rtrim(BILLID) = @REFERBILLID
		          UPDATE   STORECGRKM  set    INVOICETYPE=0
             		           WHERE  rtrim(BILLID) = @REFERBILLID  AND INVOICEAMT=0
			
		END

	           IF  @REFERBILLTYPE=2 
		BEGIN
		          UPDATE   STOREXSCKM  set    INVOICEAMT=ISNULL(INVOICEAMT,0) -@INVOICENOW
             		           WHERE  rtrim(BILLID) = @REFERBILLID
		          UPDATE   STOREXSCKM  set    INVOICETYPE=0
             		           WHERE  rtrim(BILLID) = @REFERBILLID  AND INVOICEAMT=0
		END



	           IF  @REFERBILLTYPE=7 
		BEGIN
		          UPDATE   STORECGTHM  set    INVOICEAMT=ISNULL(INVOICEAMT,0) -@INVOICENOW
             		           WHERE  rtrim(BILLID) = @REFERBILLID
		          UPDATE   STORECGTHM  set    INVOICETYPE=0
             		           WHERE  rtrim(BILLID) = @REFERBILLID  AND INVOICEAMT=0
			
		END

	           IF  @REFERBILLTYPE=12 
		BEGIN
		          UPDATE   STOREXSTHM  set    INVOICEAMT=ISNULL(INVOICEAMT,0) -@INVOICENOW
             		           WHERE  rtrim(BILLID) = @REFERBILLID
		          UPDATE   STOREXSTHM  set    INVOICETYPE=0
             		           WHERE  rtrim(BILLID) = @REFERBILLID  AND INVOICEAMT=0
		END



--------------------
    fetch SM_Consign_INVOICE_DEL into @REFERBILLID,@INVOICENOW,@ITEMNO,@REFERBILLTYPE

    END           ------- SM_Consign_INVOICE_DEL  WHILE

    close SM_Consign_INVOICE_DEL
    deallocate SM_Consign_INVOICE_DEL






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG


















CREATE PROCEDURE [STORE_JGD]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---是否现款标志
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @VENDORID   varchar(15)               --明细存货编号
declare @bankID   varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @RATE NUMERIC(20,10)                          --单据总金额
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @SUMAMT NUMERIC(20,10)                          --单据总金额
declare @UNITQTY NUMERIC(20,10)                          --单据总金额
declare @refqty NUMERIC(20,10)                          --引用数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @PRICETYPE INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

     set @BillDate =   (select BillDate  from STOREJGDM where rtrim(BILLID) = @BILLID)
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     

    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END

if  (select isnull(flagPost,0) from STOREJGDM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_JGD   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREJGDM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREJGDM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREJGDM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREJGDM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREJGDM where rtrim(BILLID) = @BILLID)
     set @VENDORID =   (select  VENDORID  from STOREJGDM where rtrim(BILLID) = @BILLID)
     set @BANKID =   (select BANKID  from STOREJGDM where rtrim(BILLID) = @BILLID)   ---------付款银行


    declare SM_Consign_JGD Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(unitPRICE,0) as PRICE, 
                                                                  DetailBillFlowID,UNITQTY,PRICETYPE    from STOREJGDD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_JGD

    fetch SM_Consign_JGD into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE, @DetailBillFlowID,@UNITQTY ,@PRICETYPE

    while @@fetch_status = 0            ----开始
    begin

-------缺少检测仓库  明日解决

                                      IF NOT (exists (select * from STORE where STOREID=@STOREID))
                                     BEGIN
			      rollback transaction trans_JGD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close SM_Consign_JGD
			    deallocate SM_Consign_JGD
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@STOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_JGD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_JGD
			    deallocate SM_Consign_JGD
                                          RETURN
			END




            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)  from GOODS where  GOODSID = @GOODSID)

---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	

	IF @PRICETYPE=0  
	BEGIN
		IF   @QTY<>0
		BEGIN
		SET  @PRICE=(@UNITQTY*@PRICE)/@QTY
		END

	END

	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE   ,@DetailBillFlowID  , @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     isnull(@REFQTY,0),0 )    
	          UPDATE   STOREJGDD  set    DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_JGD


-----------====================2012-09-04 begin

	IF   @INF_COSTINGTYPEID=6 
	Begin

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,2,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     isnull(@REFQTY,0),0 )    

-----///===	update DetailBillFlow  where ID=@NEWID
	END
-----------====================2012-09-04 end

--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END


--------------------
    fetch SM_Consign_JGD into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE, @DetailBillFlowID,@UNITQTY ,@PRICETYPE

    END           ------- SM_Consign_JGD  WHILE

    close SM_Consign_JGD
    deallocate SM_Consign_JGD

   update  STOREJGDM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
   update  STOREJGDD  set   AMT  =  Round(ISNULL(quantity,0)*ISNULL(UNITprice,0),2)               where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STOREJGDD  set   AMT  =  Round(ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)   where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0
    

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_JGD
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_JGD
      set @flagreturn = 0
   end
end














----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_JGD_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @billtype   INT
declare @SFLAG   INT
declare @INF_COSTINGTYPEID  INT                ---本期期初加权价
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE from STOREJGDM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREJGDM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_JGD_DEL   --事物开始

	     set @BillType =   (select BillType  from STOREJGDM where rtrim(BILLID) = @BILLID)

    declare SM_Consign_JGD_DEL Cursor for Select GOODSID,DetailBillFlowID,STOREID,BILLID    from STOREJGDD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_JGD_DEL

    fetch SM_Consign_JGD_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@BILLID

    while @@fetch_status = 0            ----开始
    begin
                             DELETE   DetailBillFlow     WHERE  ID=@DetailBillFlowID
--------------------------------------以上是删除一条单据明细
       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END


		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@STOREID AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
    fetch SM_Consign_JGD_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@BILLID

    END           ------- SM_Consign_JGD_DEL  WHILE

    close SM_Consign_JGD_DEL
    deallocate SM_Consign_JGD_DEL

                             DELETE   DetailBillFlow     WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 AND BILLTYPE=@billtype
--------------------------------------以上上全部删除单据  是解决多次记帐失败的问题

   update  STOREJGDM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_JGD_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_JGD_DEL
      set @flagreturn = 0
   end
end






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG
























----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_LIUH]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ClientFlag int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ITEMNO varchar(15)               --明细存货编号
declare @YunShuDWID varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号、
declare @CLIENTID varchar(15)               --明细存货编号、
declare @VENDORID varchar(15)               --明细存货编号、
declare @INStoreID varchar(15)               --明细存货编号、
declare @SUMAMT  NUMERIC(20,10)               --明细存货编号、
declare @RATE  NUMERIC(20,10)               --明细存货编号、
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @STOREIDEqty NUMERIC(20,10)                          --仓库数量
declare @REFqty NUMERIC(20,10)                          --数量
declare @UNITqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @PRICETYPE  NUMERIC(20,10)               --含税单价
declare @KEYONGQTY  NUMERIC(20,10)               --含税单价
declare @TAXRATE NUMERIC(20,10)               --含税单价
declare @APRICE  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID  varchar(50)
declare @GOODSNAME varchar(30)                     --序列号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @REITEMNO VARCHAR(25)
declare @BILLDATE DATEtime
declare @SFLAG  INTEGER
declare @YYYYMM_FLAG  INTEGER
declare @count  INTEGER
declare @MaxRate  NUMERIC(20,10)               --含税单价
declare @MinRate  NUMERIC(20,10)               --含税单价
declare @DMinSPrice NUMERIC(20,10)               --含税单价

declare @STOREHSFS   INTEGER
declare @ZhongLiangXZ   INTEGER
declare @XSPriceXZ   INTEGER
declare @NEGCLOSEOFF   bit
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
       SELECT    @NEGCLOSEOFF=(SELECT  NEGCLOSEOFF  FROM   ACCINFO    WHERE   GUID='0001' )           

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )  
         


set @BILLID   = ltrim(rtrim(@BILLID))
SET  @RETURNSTRING='  '
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @ZhongLiangXZ   = (select optionvalue from accoptions where optionname ='ZhongLiangXZ')     
     set @XSPriceXZ   = (select optionvalue from accoptions where optionname ='XSPriceXZ')     

     set @BillDate =   (select BillDate  from STORELIUHM where rtrim(BILLID) = @BILLID)

    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 


      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END


if  (select isnull(flagPost,0) from STORELIUHM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_LIUH   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STORELIUHM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STORELIUHM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STORELIUHM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STORELIUHM where rtrim(BILLID) = @BILLID)
     set @CLIENTID =   (select CLIENTID  from STORELIUHM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STORELIUHM where rtrim(BILLID) = @BILLID)
     set @ClientFLAG =   (select  ISNULL(ClientFLAG,1)   from STORELIUHM where rtrim(BILLID) = @BILLID)
     set @INStoreID =   (select BuMenID  from  STORELIUHM where rtrim(BILLID) = @BILLID)   ---------收款银行


   	 SELECT @SUMAMT= (SELECT SUM(ROUND(DISC*0.01*unitprice*UNITQTY*(1+ISNULL(TAXRATE,0)*0.01),2)) FROM   STORELIUHD  where rtrim(BILLID) = @BILLID)
   	 SELECT @SUMAMT=0


                                      IF NOT (exists (select * from ViewCLIENT where CLIENTID=@CLIENTID   and CLIENTFLAG=@CLIENTFLAG))
                                     BEGIN
			      rollback transaction  trans_LIUH 
			      set @flagreturn = 0
                                              SET @RETURNSTRING='客户不能为空或客户不存在，单据不能记帐'
                                          RETURN
			END




    declare SM_Consign_STORELIUHM Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(UNITPRICE,0)*ISNULL(DISC,0)*0.01 as PRICE, 
                                                                   REDetailBillFlowID,ISNULL(UNITQTY,0) AS UNITQTY  ,PRICETYPE,TAXRATE  from STORELIUHD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_STORELIUHM

    fetch SM_Consign_STORELIUHM into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY,@PRICETYPE,@TAXRATE 

    while @@fetch_status = 0            ----开始
    begin


            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)  from GOODS where  GOODSID = @GOODSID)


---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	


	IF @PRICETYPE=1   
	BEGIN
   	 SELECT @SUMAMT=@SUMAMT+ROUND(@price*@QTY*(1+ISNULL(@TAXRATE,0)*0.01),2)
	END
	IF @PRICETYPE=0  
	BEGIN
   	 SELECT @SUMAMT=@SUMAMT+ROUND(@price*@UNITQTY*(1+ISNULL(@TAXRATE,0)*0.01),2)

		IF   @QTY<>0
		BEGIN
		SET  @PRICE=(@UNITQTY*@PRICE)/@QTY
		END

	END



------------------------------------------

                                        IF NOT (exists (select * from STORE where STOREID=@STOREID))
                                     BEGIN
			      rollback transaction trans_LIUH
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close  SM_Consign_STORELIUHM
			    deallocate  SM_Consign_STORELIUHM
                                          RETURN
			END
--------------------------------------------
------------更改为数量库存报警
                        IF    @NEGCLOSEOFF=0 
			BEGIN 
--	                             	 EXEC   GETGOODSIDEQTY  @STOREID,@GOODSID,@YYYYMM,@EQTY=@STOREIDEQTY   OUTPUT
	                             	 EXEC   GETGOODSIDMEQTY  @STOREID,@GOODSID,@YYYYMM,@MEQTY=@STOREIDEQTY   OUTPUT

	                                        IF @UNITQTY >  ISNULL(@STOREIDEQTY,0)
             		                        BEGIN
                          		                  SET  @GOODSNAME =(SELECT NAME  FROM GOODS WHERE GOODSID=@GOODSID)
				      rollback transaction trans_LIUH
				      set @flagreturn = 0
             		                                 SET @RETURNSTRING='此'+@GOODSNAME+'库存不足不能记帐'
				    close  SM_Consign_STORELIUHM
				    deallocate  SM_Consign_STORELIUHM
	                                          RETURN
				END
			END

--------------------------------------------

            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)

	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE ,@REDetailBillFlowID,  @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',-1,@QTY*@PRICE,null,
	     0,0   )    
--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

                      select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID         -----------反填的是吨价格
	          UPDATE     STORELIUHD     set    APRICE=@APRICE,  DetailBillFlowID=@NEWID
           		           WHERE CURRENT OF  SM_Consign_STORELIUHM


-------------------------------以上解决出库-----以下解决入库

	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE ,@REDetailBillFlowID,  @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@INStoreID,'F',1,@QTY*@PRICE,null,
	     0,0   )    




--------------------------------------------------------------------------
    fetch SM_Consign_STORELIUHM into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY,@PRICETYPE,@TAXRATE 


    END           ------- SM_Consign_STORELIUHM  WHILE

    close SM_Consign_STORELIUHM
    deallocate SM_Consign_STORELIUHM

-------------------





   update  STORELIUHM  set  flagPost = 1,YYYYMM =@BILLYYYYMM   ,SUMAMT=VendorHKSum ,INVOICEAMT=0          where ltrim(rtrim(BILLID)) = @BILLID 
   update  STORELIUHD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)          where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STORELIUHD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)   where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_LIUH
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_LIUH
      set @flagreturn = 0
   end
end












----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG




















----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_LIUH_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare  @INF_COSTINGTYPEID  INT
declare  @ClientFlag  INT
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @CLIENTID varchar(10)                   --单句会计年月     
declare @VENDORID varchar(10)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @ChaCheSID VARCHAR(25)
declare @INSTOREID    varchar(15)               --明细存货编号

declare @STOREID    varchar(15)               --明细存货编号
declare @REDetailBillFlowID   varchar(30)                     --序列号
declare @REITEMNO   varchar(30)                     --序列号
declare @QUANTITY   NUMERIC(20,10)                     --序列号
declare @UNITQTY   NUMERIC(20,10)                     --序列号
declare @BILLTYPE   INTEGER
declare @SFLAG   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

                                              SET @RETURNSTRING='   '


	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STORELIUHM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STORELIUHM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_LIUH_DEL   --事物开始

     set @BillType =   (select BillType  from STORELIUHM where rtrim(BILLID) = @BILLID)
     set @INStoreID =   (select BuMenID  from  STORELIUHM where rtrim(BILLID) = @BILLID)   ---------收款银行

		DELETE    DetailBillFlow    WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@billTYPE

		DELETE    DetailBillFlow    WHERE  ltrim(rtrim(BILLID)) = '00'+Substring(@BILLID,3,6)  AND YYYYMMBILL=1
							  AND  BILLTYPE=@billTYPE
------------------------------------以上是删除全部单据明细

    declare SM_Consign_LIUH_DEL Cursor for Select GOODSID,DetailBillFlowID,STOREID,REDetailBillFlowID ,QUANTITY,UNITQTY   from STORELIUHD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_LIUH_DEL

    fetch SM_Consign_LIUH_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@REDetailBillFlowID,@QUANTITY,@UNITQTY

    while @@fetch_status = 0            ----开始
    begin
       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID

                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                             execute      APRICECACULATOR_STORE   @GOODSID,@INSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
	                             execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
	                             execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@INSTOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@INSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
             		                execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
             		                execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@INSTOREID,@YYYYMM
				     END
                            END






     update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@STOREID AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
    fetch SM_Consign_LIUH_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@REDetailBillFlowID,@QUANTITY,@UNITQTY

    END           ------- SM_Consign_LIUH_DEL  WHILE

    close SM_Consign_LIUH_DEL
    deallocate SM_Consign_LIUH_DEL








   update  STORELIUHM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_LIUH_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_LIUH_DEL
      set @flagreturn = 0
   end
end











----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













--------------------------------------------------------------------

CREATE PROCEDURE [STORE_MOVE]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。


declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)

declare @bill_type int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @BANKID varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @CLIENTID   varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @SUMAMT NUMERIC(20,10)                          --数量
declare @refqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @INBANKID VARCHAR(25)
declare @BILLDATE DATEtime
declare @MINBILLDATE DATEtime
declare @MAXBILLDATE DATEtime
declare @B_CODE VARCHAR(25)
declare @V_DATE DATEtime
declare @B_ID INTEGER
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))


     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @BillDate =   (select BillDate  from STOREMOVEM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END



if  (select isnull(flagPost,0) from STOREMOVEM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_MOVE   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREMOVEM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREMOVEM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREMOVEM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREMOVEM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  SFLAG  from STOREMOVEM where rtrim(BILLID) = @BILLID)
     set @INBANKID =   (select  VENDORID  from STOREMOVEM where rtrim(BILLID) = @BILLID)     ----实际上是出
     set @BANKID =   (select  BUMENID  from STOREMOVEM where rtrim(BILLID) = @BILLID)


                                      IF NOT (exists (select * from BANK where BANKID=@BANKID))
                                     BEGIN
			      rollback transaction trans_MOVE
			      set @flagreturn = 0
                                              SET @RETURNSTRING='银行科目不能为空或银行科目不存在，单据不能记帐'
                                          RETURN
			END

                                      IF @INBANKID=@BANKID
                                     BEGIN
			      rollback transaction trans_MOVE
			      set @flagreturn = 0
                                              SET @RETURNSTRING='银行科目不能相同，单据不能记帐'
                                          RETURN
			END
   	 SELECT @SUMAMT= (SELECT isnull(DISCAMT,0)  FROM  STOREMOVEM   where rtrim(BILLID) = @BILLID)

                                      IF @SUMAMT=0
                                     BEGIN
			      rollback transaction trans_MOVE
			      set @flagreturn = 0
                                              SET @RETURNSTRING='金额不能为0，单据不能记帐'
                                          RETURN
			END

------------------------------以下是解决科目帐的算法
            IF   (not exists(select *  from BANKBILLFLOW  where 
             		                                    (rtrim(BANKID) = @INBANKID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@INBANKID,
		     0,0,Null,
		     @inoutFlag,0  )    
            END      ------IF   END
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@INBANKID,
		     0,@SUMAMT,Null,
		     -1,0  )    
                            execute      BANK_CACULATOR_YYYYMM   @INBANKID,@YYYYMM
------------------------------------
            IF   (not exists(select *  from BANKBILLFLOW  where 
             		                                    (rtrim(BANKID) = @BANKID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,0,Null,
		     @inoutFlag,0  )    
            END      ------IF   END
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,@SUMAMT,Null,
		     1,0  )    
                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM

   update  STOREMOVEM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_MOVE
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_MOVE
      set @flagreturn = 0
   end
end





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_MOVE_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @BANKID    varchar(15)               --明细存货编号
declare @INBANKID    varchar(15)               --明细存货编号
declare @CLIENTID   varchar(30)                     --序列号
declare @INF_COSTINGTYPEID   INT
declare @REFQTY   NUMERIC(20,10)
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STOREMOVEM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREMOVEM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_MOVE_DEL   --事物开始


	     set @INBANKID =   (select  VENDORID  from STOREMOVEM where rtrim(BILLID) = @BILLID)



		DELETE   BANKBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=11

                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM
                            execute      BANK_CACULATOR_YYYYMM   @INBANKID,@YYYYMM


   update  STOREMOVEM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_MOVE_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_MOVE_DEL
      set @flagreturn = 0
   end
end





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG






















----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_QGAD]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @MStoreID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号、
declare @CLIENTID varchar(15)               --明细存货编号、
declare @SUMAMT  NUMERIC(20,10)               --明细存货编号、
declare @goodsid varchar(15)               --明细存货编号
declare @Mgoodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @STOREIDEqty NUMERIC(20,10)                          --仓库数量
declare @REFqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @RATE  NUMERIC(20,10)               --含税单价
declare @APRICE  NUMERIC(20,10)               --含税单价
declare @UNITQTY  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID  varchar(50)
declare @DetailBillFlowID  varchar(50)
declare @GOODSNAME varchar(30)                     --序列号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @SFLAG  INTEGER
declare @PRICETYPE  INTEGER
declare @YYYYMM_FLAG  INTEGER
declare @count  INTEGER
declare @STOREHSFS   INTEGER
declare @NEGCLOSEOFF   bit
declare @MaxRate  NUMERIC(20,10)               --含税单价
declare @MinRate  NUMERIC(20,10)               --含税单价
declare @DMinSPrice NUMERIC(20,10)               --含税单价
declare @ZhongLiangXZ   INTEGER
declare @XSPriceXZ   INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @NEGCLOSEOFF=(SELECT  NEGCLOSEOFF  FROM   ACCINFO    WHERE   GUID='0001' )           

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           


set @BILLID   = ltrim(rtrim(@BILLID))
SET  @RETURNSTRING='  '
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @ZhongLiangXZ   = (select optionvalue from accoptions where optionname ='ZhongLiangXZ')     
     set @XSPriceXZ   = (select optionvalue from accoptions where optionname ='XSPriceXZ')     

     set @BillDate =   (select BillDate  from STOREQGADM where rtrim(BILLID) = @BILLID)
    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 


      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END


if  (select isnull(flagPost,0) from STOREQGADM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_QGAD   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREQGADM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREQGADM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREQGADM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREQGADM where rtrim(BILLID) = @BILLID)
     set @CLIENTID =   (select CLIENTID  from STOREQGADM where rtrim(BILLID) = @BILLID)
     set @MStoreID =   (select StoreID  from STOREQGADM where rtrim(BILLID) = @BILLID)
     set @MGOODSID =   (select GOODSID  from STOREQGADM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREQGADM where rtrim(BILLID) = @BILLID)



                                        IF NOT (exists (select * from GOODS where GOODSID=@MGOODSID))
                                     BEGIN
			      rollback transaction trans_QGAD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='加工的成品件不能为空，单据不能记帐'
                                          RETURN
			END

                                        IF NOT (exists (select * from STORE where STOREID=@MStoreID))
                                     BEGIN
			      rollback transaction trans_QGAD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库不能为空或仓库不存在，单据不能记帐'
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@MStoreID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_QGAD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
                                          RETURN
			END
	    select  @UNITQTY = (select SumQTY  from STOREQGADM where rtrim(BILLID) = @BILLID)


			declare @FuKuCunOUTQty int    ---1代表数量提示，0代表重量提示
			declare @BiJiaoQTY  NUMERIC(20,10)  ---比较过度用的变量


		        set @FuKuCunOUTQty  = (select optionvalue from accoptions where optionname ='FuKuCunOUTQty')     
		
                        IF    @NEGCLOSEOFF=0 
			BEGIN 
				IF @FuKuCunOUTQty=1
				BEGIN 
	                             	EXEC   GETGOODSIDMEQTY  @MSTOREID,@MGOODSID,@YYYYMM,@MEQTY=@STOREIDEQTY   OUTPUT
					SET @BiJiaoQTY=@UNITQTY
				END
				ELSE
				BEGIN 
	                             	EXEC   GETGOODSIDEQTY  @MSTOREID,@MGOODSID,@YYYYMM,@EQTY=@STOREIDEQTY   OUTPUT				
					select  @BiJiaoQTY = (select INVOICEAMT  from STOREQGADM where rtrim(BILLID) = @BILLID)
----					SET @BiJiaoQTY=@QTY
				END
                                IF @BiJiaoQTY >  ISNULL(@STOREIDEQTY,0)
             		                        BEGIN
                          		                  SET  @GOODSNAME =(SELECT NAME  FROM GOODS WHERE GOODSID=@MGOODSID)
				      rollback transaction trans_QGAD
				      set @flagreturn = 0
             		                                 SET @RETURNSTRING='此'+@GOODSNAME+'库存不足不能记帐'
	                                          RETURN
				END
			END



    declare SM_Consign_QGAD Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(unitPRICE,0) as PRICE, 
                                                                  REDetailBillFlowID,UNITQTY,PRICETYPE    from STOREQGADD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_QGAD

    fetch SM_Consign_QGAD into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY,@PRICETYPE
    while @@fetch_status = 0            ----开始
    begin
                                        IF NOT (exists (select * from STORE where STOREID=@STOREID))
                                     BEGIN
			      rollback transaction trans_QGAD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库不能为空或仓库不存在，单据不能记帐'
			    close  SM_Consign_QGAD
			    deallocate  SM_Consign_QGAD
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@STOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_QGAD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_QGAD
			    deallocate SM_Consign_QGAD
                                          RETURN
			END




            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)  from GOODS where  GOODSID = @GOODSID)

---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	

	IF @PRICETYPE=0  
	BEGIN
		IF   @QTY<>0
		BEGIN
		SET  @PRICE=(@UNITQTY*@PRICE)/@QTY
		END

	END

	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE   ,@DetailBillFlowID  , @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     isnull(@REFQTY,0),0 )    
	          UPDATE   STOREQTRKD  set    DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_QTRK


-----------====================2012-09-04 begin

	IF   @INF_COSTINGTYPEID=6 
	Begin

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,2,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     isnull(@REFQTY,0),0 )    

-----///===	update DetailBillFlow  where ID=@NEWID
	END
-----------====================2012-09-04 end

--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

--------------------
    fetch SM_Consign_QGAD into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY,@PRICETYPE

    END           ------- SM_Consign_QGAD  WHILE

    close SM_Consign_QGAD
    deallocate SM_Consign_QGAD

--------------------------------
-----------------------------以下是入库部分

	    set @GOODSID=@MGOODSID
	    set @StoreID =   (select StoreID  from STOREQGADM where rtrim(BILLID) = @BILLID)
	    select  @QTY = (select INVOICEAMT  from STOREQGADM where rtrim(BILLID) = @BILLID)
	    select  @PRICE = (select SumAMT  from STOREQGADM where rtrim(BILLID) = @BILLID)
	    select  @UNITQTY = (select SumQTY  from STOREQGADM where rtrim(BILLID) = @BILLID)
	    select  @PRICETYPE = (select PRICETYPE  from STOREQGADM where rtrim(BILLID) = @BILLID)

            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)  from GOODS where  GOODSID = @GOODSID)

---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	

	IF @PRICETYPE=0  
	BEGIN
		IF   @QTY<>0
		BEGIN
		SET  @PRICE=(@UNITQTY*@PRICE)/@QTY
		END

	END

	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE   ,@DetailBillFlowID  , @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',-1,@QTY*@PRICE,null, 
	     isnull(@REFQTY,0),0 )    
/*	          UPDATE   STOREQGADD  set    DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_QGAD
*/

--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END







   update  STOREQGADM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
   update  STOREQGADD  set   AMT  =  Round(ISNULL(quantity,0)*ISNULL(UNITprice,0),2)               where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STOREQGADD  set   AMT  =  Round(ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)            where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_QGAD
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_QGAD
      set @flagreturn = 0
   end
end














----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG






----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_QGAD_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare  @INF_COSTINGTYPEID  INT
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @CLIENTID varchar(10)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @REDetailBillFlowID   varchar(30)                     --序列号
declare @QUANTITY   NUMERIC(20,10)                     --序列号
declare @BILLTYPE   INTEGER
declare @SFLAG   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

                                              SET @RETURNSTRING='   '


	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @YYYYMMBILL =   (select YYYYMM  from STOREQGADM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREQGADM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_QGAD_DEL   --事物开始

     set @BillType =   (select BillType  from STOREQGADM where rtrim(BILLID) = @BILLID)


    declare SM_Consign_QGAD_DEL Cursor for Select GOODSID,DetailBillFlowID,STOREID,REDetailBillFlowID ,QUANTITY  from STOREQGADD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_QGAD_DEL

    fetch SM_Consign_QGAD_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@REDetailBillFlowID,@QUANTITY

    while @@fetch_status = 0            ----开始
    begin

                             DELETE   DetailBillFlow   WHERE  ID=@DetailBillFlowID
       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@STOREID AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
    fetch SM_Consign_QGAD_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@REDetailBillFlowID,@QUANTITY

    END           ------- SM_Consign_QGAD_DEL  WHILE

    close SM_Consign_QGAD_DEL
    deallocate SM_Consign_QGAD_DEL

		DELETE    DetailBillFlow    WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND (YYYYMMBILL in (1,2))
							  AND  BILLTYPE=@billTYPE
------------------------------------以上是删除全部单据明细
     set @StoreID =   (select StoreID  from STOREQGADM where rtrim(BILLID) = @BILLID)
     set @GoodsID =   (select GoodsID  from STOREQGADM where rtrim(BILLID) = @BILLID)
       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END






   update  STOREQGADM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_QGAD_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_QGAD_DEL
      set @flagreturn = 0
   end
end










----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG
































----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_QGD]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @MStoreID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号、
declare @CLIENTID varchar(15)               --明细存货编号、
declare @SUMAMT  NUMERIC(20,10)               --明细存货编号、
declare @goodsid varchar(15)               --明细存货编号
declare @Mgoodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @STOREIDEqty NUMERIC(20,10)                          --仓库数量
declare @REFqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @RATE  NUMERIC(20,10)               --含税单价
declare @APRICE  NUMERIC(20,10)               --含税单价
declare @UNITQTY  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID  varchar(50)
declare @DetailBillFlowID  varchar(50)
declare @GOODSNAME varchar(30)                     --序列号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @SFLAG  INTEGER
declare @PRICETYPE  INTEGER
declare @YYYYMM_FLAG  INTEGER
declare @count  INTEGER
declare @STOREHSFS   INTEGER
declare @NEGCLOSEOFF   bit
declare @MaxRate  NUMERIC(20,10)               --含税单价
declare @MinRate  NUMERIC(20,10)               --含税单价
declare @DMinSPrice NUMERIC(20,10)               --含税单价
declare @ZhongLiangXZ   INTEGER
declare @XSPriceXZ   INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @NEGCLOSEOFF=(SELECT  NEGCLOSEOFF  FROM   ACCINFO    WHERE   GUID='0001' )           

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           


set @BILLID   = ltrim(rtrim(@BILLID))
SET  @RETURNSTRING='  '
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @ZhongLiangXZ   = (select optionvalue from accoptions where optionname ='ZhongLiangXZ')     
     set @XSPriceXZ   = (select optionvalue from accoptions where optionname ='XSPriceXZ')     

     set @BillDate =   (select BillDate  from STOREQGDM where rtrim(BILLID) = @BILLID)
    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END


if  (select isnull(flagPost,0) from STOREQGDM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_QGD   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @CLIENTID =   (select CLIENTID  from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @MStoreID =   (select VendorID  from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @MGOODSID =   (select GOODSID  from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREQGDM where rtrim(BILLID) = @BILLID)




                                        IF NOT (exists (select * from STORE where STOREID=@MStoreID))
                                     BEGIN
			      rollback transaction trans_QGD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库不能为空或仓库不存在，单据不能记帐'
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@MStoreID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_QGD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
                                          RETURN
			END



    declare SM_Consign_QGD_IN Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(PRICE,0) as PRICE, 
                                                                  REDetailBillFlowID,UNITQTY,PRICETYPE    from STOREQGDS where rtrim(BILLID) = @BILLID 

    Open SM_Consign_QGD_IN

    fetch SM_Consign_QGD_IN into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY,@PRICETYPE
    while @@fetch_status = 0            ----开始
    begin

                                        IF NOT (exists (select * from STORE where STOREID=@STOREID))
                                     BEGIN
			      rollback transaction trans_QGD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库不能为空或仓库不存在，单据不能记帐'
			    close  SM_Consign_QGD_IN
			    deallocate  SM_Consign_QGD_IN
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@STOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_QGD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_QGD_IN
			    deallocate SM_Consign_QGD_IN
                                          RETURN
			END




			declare @FuKuCunOUTQty int    ---1代表数量提示，0代表重量提示
			declare @BiJiaoQTY  NUMERIC(20,10)  ---比较过度用的变量


		        set @FuKuCunOUTQty  = (select optionvalue from accoptions where optionname ='FuKuCunOUTQty')     
		
                        IF    @NEGCLOSEOFF=0 
			BEGIN 
				IF @FuKuCunOUTQty=1
				BEGIN 
	                             	EXEC   GETGOODSIDMEQTY  @STOREID,@GOODSID,@YYYYMM,@MEQTY=@STOREIDEQTY   OUTPUT
					SET @BiJiaoQTY=@UNITQTY
				END
				ELSE
				BEGIN 
	                             	EXEC   GETGOODSIDEQTY  @STOREID,@GOODSID,@YYYYMM,@EQTY=@STOREIDEQTY   OUTPUT				
					SET @BiJiaoQTY=@QTY
				END
                                IF @BiJiaoQTY >  ISNULL(@STOREIDEQTY,0)
             		                        BEGIN
                          		                  SET  @GOODSNAME =(SELECT NAME  FROM GOODS WHERE GOODSID=@GOODSID)
				      rollback transaction trans_QGD
				      set @flagreturn = 0
             		                                 SET @RETURNSTRING='此'+@GOODSNAME+'库存不足不能记帐'
				    close  SM_Consign_QGD_IN
				    deallocate  SM_Consign_QGD_IN
	                                          RETURN
				END
			END

            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)  from GOODS where  GOODSID = @GOODSID)




---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	




	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE  ,@REDetailBillFlowID,  @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',-1,@QTY*@PRICE,null,
	     0,0   )    

--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

-------------------其实三种成本价的核算方式都一样                    
--------反填成本单价
		IF   @SFLAG=0   --------反填
		BEGIN
			IF @PRICETYPE=1    ----吨
			BEGIN
	                   	   select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID
			          UPDATE     STOREQGDD     set    APRICE=@APRICE,UNITPRICE=@APRICE,  DetailBillFlowID=@NEWID
             		    	       WHERE CURRENT OF  SM_Consign_QGD_IN
			END

			IF @PRICETYPE=0    ----数量
			BEGIN
		                      select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID
			          UPDATE     STOREQGDD     set    APRICE=@APRICE,UNITPRICE=@APRICE*@QTY/@UNITQTY,  DetailBillFlowID=@NEWID
	             		    	       WHERE CURRENT OF  SM_Consign_QGD_IN
			END

		END
		IF   @SFLAG=1   --------反填
		BEGIN
			          UPDATE     STOREQGDD     set      DetailBillFlowID=@NEWID
             			           WHERE CURRENT OF  SM_Consign_QGD_IN
		END

--------------------
    fetch SM_Consign_QGD_IN into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY,@PRICETYPE

    END           ------- SM_Consign_QGD_IN  WHILE

    close SM_Consign_QGD_IN
    deallocate SM_Consign_QGD_IN

--------------------------------
-----------------------------以下是入库部分
	set @STOREID=@MStoreID


    declare SM_Consign_QGD_IN Cursor for Select  ITEMNO,GOODSID, isnull(QUANTITY,0) as qty,isnull(unitPRICE,0) as PRICE, 
                                                                  DetailBillFlowID,UNITQTY,PRICETYPE    from STOREQGDD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_QGD_IN

    fetch SM_Consign_QGD_IN into @ITEMNO,@GOODSID,@qty,@PRICE, @DetailBillFlowID,@UNITQTY ,@PRICETYPE

    while @@fetch_status = 0            ----开始
    begin

-------缺少检测仓库  明日解决



            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)  from GOODS where  GOODSID = @GOODSID)

---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	

	IF @PRICETYPE=0  
	BEGIN
		IF   @QTY<>0
		BEGIN
		SET  @PRICE=(@UNITQTY*@PRICE)/@QTY
		END

	END

	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE   ,@DetailBillFlowID  , @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     isnull(@REFQTY,0),0 )    
	          UPDATE   STOREQGDD  set    DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_QGD_IN


-----------====================2012-09-04 begin

	IF   @INF_COSTINGTYPEID=6 
	Begin

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,2,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     isnull(@REFQTY,0),0 )    

-----///===	update DetailBillFlow  where ID=@NEWID
	END
-----------====================2012-09-04 end

--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END


--------------------
    fetch SM_Consign_QGD_IN into @ITEMNO,@GOODSID,@qty,@PRICE, @DetailBillFlowID,@UNITQTY ,@PRICETYPE

    END           ------- SM_Consign_QGD_IN  WHILE

    close SM_Consign_QGD_IN
    deallocate SM_Consign_QGD_IN  


   update  STOREQGDM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
   update  STOREQGDD  set   AMT  =  Round(ISNULL(quantity,0)*ISNULL(UNITprice,0),2)               where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STOREQGDD  set   AMT  =  Round(ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)            where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_QGD
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_QGD
      set @flagreturn = 0
   end
end














----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG

















----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_QGD_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare  @INF_COSTINGTYPEID  INT
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @CLIENTID varchar(10)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @REDetailBillFlowID   varchar(30)                     --序列号
declare @QUANTITY   NUMERIC(20,10)                     --序列号
declare @BILLTYPE   INTEGER
declare @SFLAG   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

                                              SET @RETURNSTRING='   '


	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STOREQGDM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREQGDM where ltrim(rtrim(BILLID)) = @BILLID ) = 0 
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_QGD_DEL   --事物开始

     set @BillType =   (select BillType  from STOREQGDM where rtrim(BILLID) = @BILLID)
		DELETE    DetailBillFlow    WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND (YYYYMMBILL in (1,2))
							  AND  BILLTYPE=@billTYPE


    declare SM_Consign_QGD_DEL Cursor for Select GOODSID,DetailBillFlowID,STOREID,REDetailBillFlowID ,QUANTITY  from STOREQGDS where rtrim(BILLID) = @BILLID 

    Open SM_Consign_QGD_DEL

    fetch SM_Consign_QGD_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@REDetailBillFlowID,@QUANTITY

    while @@fetch_status = 0            ----开始
    begin

       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

    update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@STOREID AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
    fetch SM_Consign_QGD_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@REDetailBillFlowID,@QUANTITY

    END           ------- SM_Consign_QGD_DEL  WHILE

    close SM_Consign_QGD_DEL
    deallocate SM_Consign_QGD_DEL

------------------------------------以上是删除全部单据明细
     set @StoreID =   (select VendorID  from STOREQGDM where rtrim(BILLID) = @BILLID)

    declare SM_Consign_QGD_IN_DEL Cursor for Select GOODSID,DetailBillFlowID,REDetailBillFlowID ,QUANTITY  from STOREQGDD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_QGD_IN_DEL

    fetch SM_Consign_QGD_IN_DEL into @GOODSID,@DetailBillFlowID,@REDetailBillFlowID,@QUANTITY

    while @@fetch_status = 0            ----开始
    begin

       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@STOREID AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
    fetch SM_Consign_QGD_IN_DEL into @GOODSID,@DetailBillFlowID,@REDetailBillFlowID,@QUANTITY

    END           ------- SM_Consign_QGD_IN_DEL  WHILE

    close SM_Consign_QGD_IN_DEL
    deallocate SM_Consign_QGD_IN_DEL



   update  STOREQGDM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_QGD_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_QGD_DEL
      set @flagreturn = 0
   end
end












----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG




























----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_QTCK]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号、
declare @CLIENTID varchar(15)               --明细存货编号、
declare @SUMAMT  NUMERIC(20,10)               --明细存货编号、
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @STOREIDEqty NUMERIC(20,10)                          --仓库数量
declare @REFqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @RATE  NUMERIC(20,10)               --含税单价
declare @APRICE  NUMERIC(20,10)               --含税单价
declare @UNITQTY  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID  varchar(50)
declare @GOODSNAME varchar(30)                     --序列号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @SFLAG  INTEGER
declare @PRICETYPE  INTEGER
declare @YYYYMM_FLAG  INTEGER
declare @count  INTEGER
declare @STOREHSFS   INTEGER
declare @NEGCLOSEOFF   bit
declare @MaxRate  NUMERIC(20,10)               --含税单价
declare @MinRate  NUMERIC(20,10)               --含税单价
declare @DMinSPrice NUMERIC(20,10)               --含税单价
declare @ZhongLiangXZ   INTEGER
declare @XSPriceXZ   INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @JianShu [int] 
declare @MeiJianQty [T_QUANTITY] 
declare @LingTou [T_QUANTITY] 

       SELECT    @NEGCLOSEOFF=(SELECT  NEGCLOSEOFF  FROM   ACCINFO    WHERE   GUID='0001' )           

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           


set @BILLID   = ltrim(rtrim(@BILLID))
SET  @RETURNSTRING='  '
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @ZhongLiangXZ   = (select optionvalue from accoptions where optionname ='ZhongLiangXZ')     
     set @XSPriceXZ   = (select optionvalue from accoptions where optionname ='XSPriceXZ')     

     set @BillDate =   (select BillDate  from STOREQTCKM where rtrim(BILLID) = @BILLID)

    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END


if  (select isnull(flagPost,0) from STOREQTCKM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_QTCK   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREQTCKM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREQTCKM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREQTCKM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREQTCKM where rtrim(BILLID) = @BILLID)
     set @CLIENTID =   (select CLIENTID  from STOREQTCKM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREQTCKM where rtrim(BILLID) = @BILLID)

    declare SM_Consign_QTCK Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(PRICE,0) as PRICE, 
                                                                  REDetailBillFlowID,UNITQTY,PRICETYPE,JianShu,MeiJianQty,LingTou    from STOREQTCKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_QTCK

    fetch SM_Consign_QTCK into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY,@PRICETYPE,@JianShu,@MeiJianQty,@LingTou
    while @@fetch_status = 0            ----开始
    begin
                     set @MeiJianQty =   (select ISNULL(RATE1,0)  from GOODS where  GOODSID = @GOODSID)


                            IF (ISNULL(@JianShu,0)*ISNULL(@MeiJianQty,0)+ISNULL(@LingTou,0)<>@Unitqty) AND (ISNULL(@JianShu,0)<>0 OR ISNULL(@LingTou,0)<>0)
                                     BEGIN
			      rollback transaction trans_QTCK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='件数*每件数量+零头与数量不等，单据不能记帐'
			    close  SM_Consign_QTCK
			    deallocate  SM_Consign_QTCK
                                          RETURN
			END

                                        IF NOT (exists (select * from STORE where STOREID=@STOREID))
                                     BEGIN
			      rollback transaction trans_QTCK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close  SM_Consign_QTCK
			    deallocate  SM_Consign_QTCK
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@STOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_QTCK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_QTCK
			    deallocate SM_Consign_QTCK
                                          RETURN
			END




			declare @FuKuCunOUTQty int    ---1代表数量提示，0代表重量提示
			declare @BiJiaoQTY  NUMERIC(20,10)  ---比较过度用的变量


		        set @FuKuCunOUTQty  = (select optionvalue from accoptions where optionname ='FuKuCunOUTQty')     
		
                        IF    @NEGCLOSEOFF=0 
			BEGIN 
				IF @FuKuCunOUTQty=1
				BEGIN 
	                             	EXEC   GETGOODSIDMEQTY  @STOREID,@GOODSID,@YYYYMM,@MEQTY=@STOREIDEQTY   OUTPUT
					SET @BiJiaoQTY=@UNITQTY
				END
				ELSE
				BEGIN 
	                             	EXEC   GETGOODSIDEQTY  @STOREID,@GOODSID,@YYYYMM,@EQTY=@STOREIDEQTY   OUTPUT				
					SET @BiJiaoQTY=@QTY
				END
                                IF @BiJiaoQTY >  ISNULL(@STOREIDEQTY,0)
          		        BEGIN
                          		                  SET  @GOODSNAME =(SELECT NAME  FROM GOODS WHERE GOODSID=@GOODSID)
				      rollback transaction trans_QTCK
				      set @flagreturn = 0
             		                                 SET @RETURNSTRING='此'+@GOODSNAME+'库存不足不能记帐'
				    close  SM_Consign_QTCK
				    deallocate  SM_Consign_QTCK
	                                          RETURN
				END
			END

            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)  from GOODS where  GOODSID = @GOODSID)




---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	




	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE  ,@REDetailBillFlowID,  @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',-1,@QTY*@PRICE,null,
	     0,0   )    

--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

-------------------其实三种成本价的核算方式都一样                    
--------反填成本单价
		IF   @SFLAG=0   --------反填
		BEGIN
			IF @PRICETYPE=1    ----吨
			BEGIN
	                   	   select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID
			          UPDATE     STOREQTCKD     set    APRICE=@APRICE,UNITPRICE=@APRICE,  DetailBillFlowID=@NEWID
             		    	       WHERE CURRENT OF  SM_Consign_QTCK
			END

			IF @PRICETYPE=0    ----数量
			BEGIN
		                      select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID
			          UPDATE     STOREQTCKD     set    APRICE=@APRICE,UNITPRICE=@APRICE*@QTY/@UNITQTY,  DetailBillFlowID=@NEWID
	             		    	       WHERE CURRENT OF  SM_Consign_QTCK
			END

		END
		IF   @SFLAG=1   --------反填
		BEGIN
			          UPDATE     STOREQTCKD     set      DetailBillFlowID=@NEWID
             			           WHERE CURRENT OF  SM_Consign_QTCK
		END

--------------------
    fetch SM_Consign_QTCK into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY,@PRICETYPE,@JianShu,@MeiJianQty,@LingTou

    END           ------- SM_Consign_QTCK  WHILE

    close SM_Consign_QTCK
    deallocate SM_Consign_QTCK


-------------------


   update  STOREQTCKM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
   update  STOREQTCKD  set   AMT  =  Round(ISNULL(quantity,0)*ISNULL(UNITprice,0),2)               where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STOREQTCKD  set   AMT  =  Round(ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)            where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_QTCK
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_QTCK
      set @flagreturn = 0
   end
end










----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_QTCK_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare  @INF_COSTINGTYPEID  INT
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @CLIENTID varchar(10)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @REDetailBillFlowID   varchar(30)                     --序列号
declare @QUANTITY   NUMERIC(20,10)                     --序列号
declare @BILLTYPE   INTEGER
declare @SFLAG   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间


       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

                                              SET @RETURNSTRING='   '


	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STOREQTCKM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREQTCKM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_QTCK_DEL   --事物开始

     set @BillType =   (select BillType  from STOREQTCKM where rtrim(BILLID) = @BILLID)


    declare SM_Consign_QTCK_DEL Cursor for Select GOODSID,DetailBillFlowID,STOREID,REDetailBillFlowID ,QUANTITY  from STOREQTCKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_QTCK_DEL

    fetch SM_Consign_QTCK_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@REDetailBillFlowID,@QUANTITY

    while @@fetch_status = 0            ----开始
    begin

                             DELETE   DetailBillFlow   WHERE  ID=@DetailBillFlowID
       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@STOREID AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
    fetch SM_Consign_QTCK_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@REDetailBillFlowID,@QUANTITY

    END           ------- SM_Consign_QTCK_DEL  WHILE

    close SM_Consign_QTCK_DEL
    deallocate SM_Consign_QTCK_DEL

		DELETE    DetailBillFlow    WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND (YYYYMMBILL in (1,2))
							  AND  BILLTYPE=@billTYPE
------------------------------------以上是删除全部单据明细

   update  STOREQTCKM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_QTCK_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_QTCK_DEL
      set @flagreturn = 0
   end
end







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG





















CREATE PROCEDURE [STORE_QTRK]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---是否现款标志
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @VENDORID   varchar(15)               --明细存货编号
declare @bankID   varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @RATE NUMERIC(20,10)                          --单据总金额
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @SUMAMT NUMERIC(20,10)                          --单据总金额
declare @UNITQTY NUMERIC(20,10)                          --单据总金额
declare @refqty NUMERIC(20,10)                          --引用数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @PRICETYPE INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @JianShu [int] 
declare @MeiJianQty [T_QUANTITY] 
declare @LingTou [T_QUANTITY] 

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

     set @BillDate =   (select BillDate  from STOREQTRKM where rtrim(BILLID) = @BILLID)
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     

    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END

if  (select isnull(flagPost,0) from STOREQTRKM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_QTRK   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREQTRKM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREQTRKM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREQTRKM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREQTRKM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREQTRKM where rtrim(BILLID) = @BILLID)
     set @VENDORID =   (select  VENDORID  from STOREQTRKM where rtrim(BILLID) = @BILLID)
     set @BANKID =   (select BANKID  from STOREQTRKM where rtrim(BILLID) = @BILLID)   ---------付款银行


    declare SM_Consign_QTRK Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(unitPRICE,0) as PRICE, 
                                                                  DetailBillFlowID,UNITQTY,PRICETYPE,JianShu,MeiJianQty,LingTou    from STOREQTRKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_QTRK

    fetch SM_Consign_QTRK into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE, @DetailBillFlowID,@UNITQTY ,@PRICETYPE,@JianShu,@MeiJianQty,@LingTou

    while @@fetch_status = 0            ----开始
    begin

-------缺少检测仓库  明日解决

                     set @MeiJianQty =   (select ISNULL(RATE1,0)  from GOODS where  GOODSID = @GOODSID)


                            IF (ISNULL(@JianShu,0)*ISNULL(@MeiJianQty,0)+ISNULL(@LingTou,0)<>@Unitqty) AND (ISNULL(@JianShu,0)<>0 OR ISNULL(@LingTou,0)<>0)
                                     BEGIN
			      rollback transaction trans_QTRK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='件数*每件数量+零头与数量不等，单据不能记帐'
			    close SM_Consign_QTRK
			    deallocate SM_Consign_QTRK
                                          RETURN
			END
                                      IF NOT (exists (select * from STORE where STOREID=@STOREID))
                                     BEGIN
			      rollback transaction trans_QTRK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close SM_Consign_QTRK
			    deallocate SM_Consign_QTRK
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@STOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_QTRK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_QTRK
			    deallocate SM_Consign_QTRK
                                          RETURN
			END




            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)  from GOODS where  GOODSID = @GOODSID)

---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	

	IF @PRICETYPE=0  
	BEGIN
		IF   @QTY<>0
		BEGIN
		SET  @PRICE=(@UNITQTY*@PRICE)/@QTY
		END

	END

	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE   ,@DetailBillFlowID  , @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     isnull(@REFQTY,0),0 )    
	          UPDATE   STOREQTRKD  set    DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_QTRK


-----------====================2012-09-04 begin

	IF   @INF_COSTINGTYPEID=6 
	Begin

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,2,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     isnull(@REFQTY,0),0 )    

-----///===	update DetailBillFlow  where ID=@NEWID
	END
-----------====================2012-09-04 end

--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END


--------------------
    fetch SM_Consign_QTRK into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE, @DetailBillFlowID,@UNITQTY ,@PRICETYPE,@JianShu,@MeiJianQty,@LingTou

    END           ------- SM_Consign_QTRK  WHILE

    close SM_Consign_QTRK
    deallocate SM_Consign_QTRK

   update  STOREQTRKM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
   update  STOREQTRKD  set   AMT  =  Round(ISNULL(quantity,0)*ISNULL(UNITprice,0),2)               where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STOREQTRKD  set   AMT  =  Round(ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)   where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0
    

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_QTRK
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_QTRK
      set @flagreturn = 0
   end
end

















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_QTRK_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @billtype   INT
declare @SFLAG   INT
declare @INF_COSTINGTYPEID  INT                ---本期期初加权价
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间


       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STOREQTRKM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREQTRKM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_QTRK_DEL   --事物开始

	     set @BillType =   (select BillType  from STOREQTRKM where rtrim(BILLID) = @BILLID)

    declare SM_Consign_QTRK_DEL Cursor for Select GOODSID,DetailBillFlowID,STOREID,BILLID    from STOREQTRKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_QTRK_DEL

    fetch SM_Consign_QTRK_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@BILLID

    while @@fetch_status = 0            ----开始
    begin
                             DELETE   DetailBillFlow     WHERE  ID=@DetailBillFlowID
--------------------------------------以上是删除一条单据明细
       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END


		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@STOREID AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
    fetch SM_Consign_QTRK_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@BILLID

    END           ------- SM_Consign_QTRK_DEL  WHILE

    close SM_Consign_QTRK_DEL
    deallocate SM_Consign_QTRK_DEL

                             DELETE   DetailBillFlow     WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 AND BILLTYPE=@billtype
--------------------------------------以上上全部删除单据  是解决多次记帐失败的问题

   update  STOREQTRKM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_QTRK_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_QTRK_DEL
      set @flagreturn = 0
   end
end






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













--------------------------------------------------------------------

CREATE PROCEDURE [STORE_QTSR]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。


declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)

declare @bill_type int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @CLIENTID   varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @SUMAMT NUMERIC(20,10)                          --数量
declare @refqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价

declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @INBANKID VARCHAR(25)
declare @BILLDATE DATEtime
declare @MINBILLDATE DATEtime
declare @MAXBILLDATE DATEtime
declare @B_CODE VARCHAR(25)
declare @V_DATE DATEtime
declare @B_ID INTEGER
declare @STOREHSFS   INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @YYYYMM_FLAG  INTEGER

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @BillDate =   (select BillDate  from STOREQTSRM where rtrim(BILLID) = @BILLID)
    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END



if  (select isnull(flagPost,0) from STOREQTSRM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_QTSR   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREQTSRM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREQTSRM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREQTSRM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREQTSRM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  SFLAG  from STOREQTSRM where rtrim(BILLID) = @BILLID)
     set @INBANKID =   (select  VENDORID  from STOREQTSRM where rtrim(BILLID) = @BILLID)


                                      IF NOT (exists (select * from BANK where BANKID=@INBANKID))
                                     BEGIN
			      rollback transaction trans_QTSR
			      set @flagreturn = 0
                                              SET @RETURNSTRING='银行科目不能为空或银行科目不存在，单据不能记帐'
                                          RETURN
			END
   	 SELECT @SUMAMT= (SELECT SUM(QUANTITY)  FROM  STOREQTSRD   where rtrim(BILLID) = @BILLID)

------------------------------以下是解决科目帐的算法
            IF   (not exists(select *  from BANKBILLFLOW  where 
             		                                    (rtrim(BANKID) = @INBANKID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@INBANKID,
		     0,0,Null,
		     @inoutFlag,0  )    
            END      ------IF   END
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@INBANKID,
		     0,@SUMAMT,Null,
		     1,0  )    
                            execute      BANK_CACULATOR_YYYYMM   @INBANKID,@YYYYMM
------------------------------------

   update  STOREQTSRM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_QTSR
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_QTSR
      set @flagreturn = 0
   end
end





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_QTSR_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 

declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @BANKID    varchar(15)               --明细存货编号
declare @INBANKID    varchar(15)               --明细存货编号
declare @CLIENTID   varchar(30)                     --序列号
declare @INF_COSTINGTYPEID   INT
declare @REFQTY   NUMERIC(20,10)
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STOREQTSRM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREQTSRM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_QTSR_DEL   --事物开始


	     set @INBANKID =   (select  VENDORID  from STOREQTSRM where rtrim(BILLID) = @BILLID)

		DELETE   BANKBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=3
                            execute      BANK_CACULATOR_YYYYMM   @INBANKID,@YYYYMM

   update  STOREQTSRM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_QTSR_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_QTSR_DEL
      set @flagreturn = 0
   end
end





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG








----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_SUM_ALL]  
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @BILLid varchar(15)               --明细存货编号
declare @SUMAMT   NUMERIC(20,10)                          --数量
----------------------不合计盘点单

     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_SUM_ALL   --事物开始


    declare YOUBIAO_QTCK Cursor for Select     BILLID   from STOREQTCKM   where flagpost=0

    Open YOUBIAO_QTCK

    fetch YOUBIAO_QTCK into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREQTCKD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREQTCKM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_QTCK into @BILLID     

    END           ------- YOUBIAO_QTCK  WHILE

    close YOUBIAO_QTCK
    deallocate YOUBIAO_QTCK

---------------------------------------------------
    declare YOUBIAO_QTCKTH Cursor for Select     BILLID   from STOREQTCKTHM   where flagpost=0

    Open YOUBIAO_QTCKTH

    fetch YOUBIAO_QTCKTH into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREQTCKTHD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREQTCKTHM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_QTCKTH into @BILLID     

    END           ------- YOUBIAO_QTCKTH  WHILE

    close YOUBIAO_QTCKTH
    deallocate YOUBIAO_QTCKTH

-------------------------------------------
    declare YOUBIAO_JYCKTH Cursor for Select     BILLID   from STOREJYCKTHM   where flagpost=0

    Open YOUBIAO_JYCKTH

    fetch YOUBIAO_JYCKTH into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREJYCKTHD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREJYCKTHM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_JYCKTH into @BILLID     

    END           ------- YOUBIAO_JYCKTH  WHILE

    close YOUBIAO_JYCKTH
    deallocate YOUBIAO_JYCKTH

-------------------------------------------------------------
    declare YOUBIAO_JYCK Cursor for Select     BILLID   from STOREJYCKM   where flagpost=0

    Open YOUBIAO_JYCK

    fetch YOUBIAO_JYCK into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREJYCKD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREJYCKM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_JYCK into @BILLID     

    END           ------- YOUBIAO_JYCK  WHILE

    close YOUBIAO_JYCK
    deallocate YOUBIAO_JYCK

-------------------------------------------------------------
    declare YOUBIAO_DBCK Cursor for Select     BILLID   from STOREDBCKM   where flagpost=0

    Open YOUBIAO_DBCK

    fetch YOUBIAO_DBCK into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREDBCKD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREDBCKM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_DBCK into @BILLID     

    END           ------- YOUBIAO_DBCK  WHILE

    close YOUBIAO_DBCK
    deallocate YOUBIAO_DBCK

-------------------------------------------------------------
    declare YOUBIAO_DBCKTH Cursor for Select     BILLID   from STOREDBCKTHM   where flagpost=0

    Open YOUBIAO_DBCKTH

    fetch YOUBIAO_DBCKTH into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREDBCKTHD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREDBCKTHM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_DBCKTH into @BILLID     

    END           ------- YOUBIAO_DBCKTH  WHILE

    close YOUBIAO_DBCKTH
    deallocate YOUBIAO_DBCKTH

-------------------------------------------------------------

    declare YOUBIAO_JYRKTH Cursor for Select     BILLID   from STOREJYRKTHM   where flagpost=0

    Open YOUBIAO_JYRKTH

    fetch YOUBIAO_JYRKTH into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREJYRKTHD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREJYRKTHM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_JYRKTH into @BILLID     

    END           ------- YOUBIAO_JYRKTH  WHILE

    close YOUBIAO_JYRKTH
    deallocate YOUBIAO_JYRKTH

-------------------------------------------------------------
    declare YOUBIAO_JYRK Cursor for Select     BILLID   from STOREJYRKM   where flagpost=0

    Open YOUBIAO_JYRK

    fetch YOUBIAO_JYRK into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREJYRKD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREJYRKM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_JYRK into @BILLID     

    END           ------- YOUBIAO_JYRK  WHILE

    close YOUBIAO_JYRK
    deallocate YOUBIAO_JYRK

-------------------------------------------------------------
    declare YOUBIAO_DBRK Cursor for Select     BILLID   from STOREDBRKM   where flagpost=0

    Open YOUBIAO_DBRK

    fetch YOUBIAO_DBRK into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREDBRKD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREDBRKM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_DBRK into @BILLID     

    END           ------- YOUBIAO_DBRK  WHILE

    close YOUBIAO_DBRK
    deallocate YOUBIAO_DBRK

-------------------------------------------------------------
    declare YOUBIAO_ZSRK Cursor for Select     BILLID   from STOREZSRKM   where flagpost=0

    Open YOUBIAO_ZSRK

    fetch YOUBIAO_ZSRK into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREZSRKD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREZSRKM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_ZSRK into @BILLID     

    END           ------- YOUBIAO_ZSRK  WHILE

    close YOUBIAO_ZSRK
    deallocate YOUBIAO_ZSRK

-------------------------------------------------------------
    declare YOUBIAO_QTRK Cursor for Select     BILLID   from STOREQTRKM   where flagpost=0

    Open YOUBIAO_QTRK

    fetch YOUBIAO_QTRK into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREQTRKD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREQTRKM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_QTRK into @BILLID     

    END           ------- YOUBIAO_QTRK  WHILE

    close YOUBIAO_QTRK
    deallocate YOUBIAO_QTRK

-------------------------------------------------------------

    declare YOUBIAO_DBRKTH Cursor for Select     BILLID   from STOREDBRKTHM   where flagpost=0

    Open YOUBIAO_DBRKTH

    fetch YOUBIAO_DBRKTH into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREDBRKTHD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREDBRKTHM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_DBRKTH into @BILLID     

    END           ------- YOUBIAO_DBRKTH  WHILE

    close YOUBIAO_DBRKTH
    deallocate YOUBIAO_DBRKTH

-------------------------------------------------------------
    declare YOUBIAO_ZSRKTH Cursor for Select     BILLID   from STOREZSRKTHM   where flagpost=0

    Open YOUBIAO_ZSRKTH

    fetch YOUBIAO_ZSRKTH into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREZSRKTHD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREZSRKTHM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_ZSRKTH into @BILLID     

    END           ------- YOUBIAO_ZSRKTH  WHILE

    close YOUBIAO_ZSRKTH
    deallocate YOUBIAO_ZSRKTH

-------------------------------------------------------------

    declare YOUBIAO_QTRKTH Cursor for Select     BILLID   from STOREQTRKTHM   where flagpost=0

    Open YOUBIAO_QTRKTH

    fetch YOUBIAO_QTRKTH into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREQTRKTHD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREQTRKTHM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_QTRKTH into @BILLID     

    END           ------- YOUBIAO_QTRKTH  WHILE

    close YOUBIAO_QTRKTH
    deallocate YOUBIAO_QTRKTH

-------------------------------------------------------------

    declare YOUBIAO_GJRK Cursor for Select     BILLID   from STOREGJRKM   where flagpost=0

    Open YOUBIAO_GJRK

    fetch YOUBIAO_GJRK into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREGJRKD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREGJRKM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_GJRK into @BILLID     

    END           ------- YOUBIAO_GJRK  WHILE

    close YOUBIAO_GJRK
    deallocate YOUBIAO_GJRK

-------------------------------------------------------------
    declare YOUBIAO_XSCK Cursor for Select     BILLID   from STOREXSCKM   where flagpost=0

    Open YOUBIAO_XSCK

    fetch YOUBIAO_XSCK into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE*DISC*0.01*(100+ISNULL(TAXRATE,0))*0.01,2))  as sumamt  from  STOREXSCKD 
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREXSCKM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_XSCK into @BILLID     

    END           ------- YOUBIAO_XSCK  WHILE

    close YOUBIAO_XSCK
    deallocate YOUBIAO_XSCK

-------------------------------------------------------------
    declare YOUBIAO_XSTH Cursor for Select     BILLID   from STOREXSTHM   where flagpost=0

    Open YOUBIAO_XSTH

    fetch YOUBIAO_XSTH into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE*DISC*0.01*(100+ISNULL(TAXRATE,0))*0.01,2))  as sumamt  from  STOREXSTHD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREXSTHM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_XSTH into @BILLID     

    END           ------- YOUBIAO_XSTH  WHILE

    close YOUBIAO_XSTH
    deallocate YOUBIAO_XSTH


----------------------    declare YOUBIAO_CGTH Cursor for Select     BILLID   from STORECGTHM   where flagpost=0

    Open YOUBIAO_CGTH

    fetch YOUBIAO_CGTH into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE*DISC*0.01*(100+ISNULL(TAXRATE,0))*0.01,2))  as sumamt  from   STORECGTHD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STORECGTHM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_CGTH into @BILLID     

    END           ------- YOUBIAO_CGTH  WHILE

    close YOUBIAO_CGTH
    deallocate YOUBIAO_CGTH

-----------------------------------------
    declare YOUBIAO_CGRK Cursor for Select     BILLID   from STORECGRKM   where flagpost=0

    Open YOUBIAO_CGRK

    fetch YOUBIAO_CGRK into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE*DISC*0.01*(100+ISNULL(TAXRATE,0))*0.01,2))  as sumamt  from   STORECGRKD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STORECGRKM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_CGRK into @BILLID     

    END           ------- YOUBIAO_CGRK  WHILE

    close YOUBIAO_CGRK
    deallocate YOUBIAO_CGRK

----------------------------------------------------------------

-------------------------------------------------------------

    declare YOUBIAO_CKDB Cursor for Select     BILLID   from STORECKDBM   where flagpost=0

    Open YOUBIAO_CKDB

    fetch YOUBIAO_CKDB into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STORECKDBD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STORECKDBM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_CKDB into @BILLID     

    END           ------- YOUBIAO_CKDB  WHILE

    close YOUBIAO_CKDB
    deallocate YOUBIAO_CKDB

-------------------------------------------------------------
    declare YOUBIAO_XSDD Cursor for Select     BILLID   from STOREXSDDM   where flagpost=0

    Open YOUBIAO_XSDD

    fetch YOUBIAO_XSDD into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE*DISC*0.01*(100+ISNULL(TAXRATE,0))*0.01,2))  as sumamt  from  STOREXSDDD 
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREXSDDM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_XSDD into @BILLID     

    END           ------- YOUBIAO_XSDD  WHILE

    close YOUBIAO_XSDD
    deallocate YOUBIAO_XSDD

-------------------------------------------------------------
    declare YOUBIAO_CGDD Cursor for Select     BILLID   from STORECGDDM   where flagpost=0

    Open YOUBIAO_CGDD

    fetch YOUBIAO_CGDD into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE*DISC*0.01*(100+ISNULL(TAXRATE,0))*0.01,2))  as sumamt  from  STORECGDDD 
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STORECGDDM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_CGDD into @BILLID     

    END           ------- YOUBIAO_CGDD  WHILE

    close YOUBIAO_CGDD
    deallocate YOUBIAO_CGDD

-------------------------------------------------------------
    

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_SUM_ALL
   end
   else
   begin
      rollback transaction trans_SUM_ALL
   end





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG



















----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_TALLY]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @TABLENAME varchar(22),      ---表名
                  @RETURNSTRING00            varchar(60)    output ,      ---单据编号   
                  @flagreturn00 int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 

declare @YYYYMM varchar(6)                   --会计年月     
declare @GOODSID varchar(30)                   --会计年月     

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')   

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREZFDM'
         BEGIN
                 execute  STORE_ZFD    @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END  
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREXSFPM'
         BEGIN
                 execute  STORE_XSFP    @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END  
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECGFPM'
         BEGIN
                 execute  STORE_CGFP    @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END  

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREXSDDM'
         BEGIN
                 execute  STORE_XSDD    @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END  

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECGDDM'
         BEGIN
                 execute  STORE_CGDD    @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END  

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORELIUHM'
         BEGIN
                 execute  STORE_LIUH    @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END  

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREGJRKM'
         BEGIN
                 execute  STORE_GJRK    @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
         IF  @TABLENAME = 'STORECGTHM'
         BEGIN
                 execute  STORE_CGTH      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREXSTHM'
         BEGIN
                 execute  STORE_XSTH      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREMOVEM'
         BEGIN
                 execute  STORE_MOVE      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREXSSKM'
         BEGIN
                 execute  STORE_XSSK      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECGFKM'
         BEGIN
                 execute  STORE_CGFK      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREXSCKM'
         BEGIN
                 execute  STORE_XSCK     @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREQTRKM'
         BEGIN
                 execute  STORE_QTRK    @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREQTCKM'
         BEGIN
                 execute  STORE_QTCK     @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREQTSRM'
         BEGIN
                 execute  STORE_QTSR     @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREFYKZM'
         BEGIN
                 execute  STORE_FYKZ    @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECKDBM'
         BEGIN
                 execute  STORE_CKDB     @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECSHM'
         BEGIN
                 execute  STORE_CSH     @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECGRKM'
         BEGIN
                 execute  STORE_CGRK     @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
        END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREYunFeiFKM'
         BEGIN
                 execute  STORE_YunFeiFK     @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
        END
-----------------------------------------------------IF  END

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECKPDM'
         BEGIN
                 execute  STORE_CKPD     @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREQGDM'
         BEGIN
                 execute  STORE_QGD     @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREJGDM'
         BEGIN
                 execute  STORE_JGD     @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREQGADM'
         BEGIN
                 execute  STORE_QGAD     @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END










----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG























----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_TALLY_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @TABLENAME varchar(22),      ---表名
                  @RETURNSTRING00            varchar(60)    output ,      ---单据编号   
                  @flagreturn00 int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 

declare @YYYYMM varchar(6)                   --会计年月     
declare @GOODSID varchar(30)                   --会计年月     

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')



-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREXSDDM'
         BEGIN
                 execute  STORE_XSDD_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END     

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORELIUHM'
         BEGIN
                 execute  STORE_LIUH_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END     

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREGJRKM'
         BEGIN
                 execute  STORE_GJRK_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREXSTHM'
         BEGIN
                 execute  STORE_XSTH_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECGTHM'
         BEGIN
                 execute  STORE_CGTH_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREMOVEM'
         BEGIN
                 execute  STORE_MOVE_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREXSSKM'
         BEGIN
                 execute  STORE_XSSK_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECGFKM'
         BEGIN
                 execute  STORE_CGFK_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREYunFeiFKM'
         BEGIN
                 execute  STORE_YunFeiFK_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECGRKM'
         BEGIN
                 execute  STORE_CGRK_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREXSCKM'
         BEGIN
                 execute  STORE_XSCK_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREQTRKM'
         BEGIN
                 execute  STORE_QTRK_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREQTCKM'
         BEGIN
                 execute  STORE_QTCK_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREQTSRM'
         BEGIN
                 execute  STORE_QTSR_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREFYKZM'
         BEGIN
                 execute  STORE_FYKZ_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECKDBM'
         BEGIN
                 execute  STORE_CKDB_DEL     @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECKPDM'
         BEGIN
                 execute  STORE_CKPD_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECSHM'
         BEGIN
                 execute  STORE_CSH_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREJGDM'
         BEGIN
                 execute  STORE_JGD_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREQGDM'
         BEGIN
                 execute  STORE_QGD_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREQGADM'
         BEGIN
                 execute  STORE_QGAD_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECGDDM'
         BEGIN
                 execute  STORE_CGDD_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREXSFPM'
         BEGIN
                 execute  STORE_XSFP_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECGFPM'
         BEGIN
                 execute  STORE_CGFP_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREZFDM'
         BEGIN
                 execute  STORE_ZFD_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END










----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG





----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[STORE_XSCK]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @BuMenID varchar(10)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ClientFlag int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ITEMNO varchar(15)               --明细存货编号
declare @YunShuDWID varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号、
declare @CLIENTID varchar(15)               --明细存货编号、
declare @VENDORID varchar(15)               --明细存货编号、
declare @BANKID varchar(15)               --明细存货编号、
declare @SUMAMT  NUMERIC(20,10)               --明细存货编号、
declare @RATE  NUMERIC(20,10)               --明细存货编号、
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @STOREIDEqty NUMERIC(20,10)                          --仓库数量
declare @REFqty NUMERIC(20,10)                          --数量
declare @UNITqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @PRICETYPE  NUMERIC(20,10)               --含税单价
declare @KEYONGunitQTY  NUMERIC(20,10)               --含税单价
declare @KEYONGquantity  NUMERIC(20,10)               --含税单价
declare @TMPunitQTY  NUMERIC(20,10)               --含税单价
declare @TMPquantity  NUMERIC(20,10)               --含税单价
declare @TAXRATE NUMERIC(20,10)               --含税单价
declare @APRICE  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID  varchar(50)
declare @GOODSNAME varchar(30)                     --序列号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @REITEMNO VARCHAR(25)
declare @BILLDATE DATEtime
declare @SFLAG  INTEGER
declare @YYYYMM_FLAG  INTEGER
declare @count  INTEGER
declare @ChaCheSID VARCHAR(25)
declare @PanYunSID VARCHAR(25)
declare @YunFeiZhiFuFX VARCHAR(25)  ----运费支付方向
declare @ChaChePrice  NUMERIC(20,10)               --含税单价
declare @PanYunPrice  NUMERIC(20,10)               --含税单价
declare @ChaCheSYunfei  NUMERIC(20,10)               --含税单价
declare @PanYunSYunfei  NUMERIC(20,10)               --含税单价
declare @QiTaFeiYong  NUMERIC(20,10)               --含税单价
declare @YunFeiSum  NUMERIC(20,10)               --含税单价
declare @MaxRate  NUMERIC(20,10)               --含税单价
declare @MinRate  NUMERIC(20,10)               --含税单价
declare @DMinSPrice NUMERIC(20,10)               --含税单价

declare @STOREHSFS   INTEGER
declare @ZhongLiangXZ   INTEGER
declare @XSPriceXZ   INTEGER
declare @NEGCLOSEOFF   bit
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @JianShu [int] 
declare @MeiJianQty [T_QUANTITY] 
declare @LingTou [T_QUANTITY] 


       SELECT    @NEGCLOSEOFF=(SELECT  NEGCLOSEOFF  FROM   ACCINFO    WHERE   GUID='0001' )           

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )  
         


set @BILLID   = ltrim(rtrim(@BILLID))
SET  @RETURNSTRING='  '
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @ZhongLiangXZ   = (select optionvalue from accoptions where optionname ='ZhongLiangXZ')     
     set @XSPriceXZ   = (select optionvalue from accoptions where optionname ='XSPriceXZ')     

     set @BillDate =   (select BillDate  from STOREXSCKM where rtrim(BILLID) = @BILLID)

    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 


      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END


if  (select isnull(flagPost,0) from STOREXSCKM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_XSCK   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREXSCKM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREXSCKM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREXSCKM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREXSCKM where rtrim(BILLID) = @BILLID)
     set @CLIENTID =   (select CLIENTID  from STOREXSCKM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREXSCKM where rtrim(BILLID) = @BILLID)
     set @ClientFLAG =   (select  ISNULL(ClientFLAG,1)   from STOREXSCKM where rtrim(BILLID) = @BILLID)
     set @BANKID =   (select BANKID  from  STOREXSCKM where rtrim(BILLID) = @BILLID)   ---------收款银行
     set @BuMenID =   (select BuMenID  from  STOREXSCKM where rtrim(BILLID) = @BILLID)   ---------收款银行

     set @ChaCheSID =   (select ChaCheSID  from STOREXSCKM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @PanYunSID =   (select PanYunSID  from STOREXSCKM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @YunFeiZhiFuFX =   (select YunFeiZhiFuFX  from STOREXSCKM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @ChaChePrice =   (select ISNULL(ChaChePrice,0)  from STOREXSCKM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @PanYunPrice =   (select ISNULL(PanYunPrice,0)  from STOREXSCKM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @ChaCheSYunFei=    (select ROUND(ISNULL(ChaChePrice,0)*SumQUANTITY,2) from STOREXSCKM where rtrim(BILLID) = @BILLID)   ---------付款银行 
     set @PanYunSYunFei=    (select ROUND(ISNULL(PanYunPrice,0)*SumQUANTITY,2) from STOREXSCKM where rtrim(BILLID) = @BILLID)   ---------付款银行 
     set @YunFeiSum=   @ChaCheSYunFei+@PanYunSYunFei
     set @QiTaFeiYong =   (select ISNULL(QiTaFeiYong,0)  from STOREXSCKM where rtrim(BILLID) = @BILLID)   ---------付款银行


   	 SELECT @SUMAMT= (SELECT SUM(ROUND(DISC*0.01*unitprice*UNITQTY*(1+ISNULL(TAXRATE,0)*0.01),2)) FROM   STOREXSCKD  where rtrim(BILLID) = @BILLID)
   	 SELECT @SUMAMT=0

                              IF (NOT exists(select * from YunShuDW where YunShuDWID=@ChaCheSID)) and @ChaChePrice<>0
                              BEGIN
			      rollback transaction trans_CGRK
			      set @flagreturn = 0
                                      SET @RETURNSTRING='叉车商不能为空或叉车商不存在，单据不能记帐'
                                       RETURN
			END

                              IF (NOT exists(select * from YunShuDW where YunShuDWID=@PanYunSID)) and @PanYunPrice<>0
                              BEGIN
			      rollback transaction trans_CGRK
			      set @flagreturn = 0
                                      SET @RETURNSTRING='盘运商不能为空或盘运商不存在，单据不能记帐'
                                       RETURN
			END

                                      IF NOT (exists (select * from ViewCLIENT where CLIENTID=@CLIENTID   and CLIENTFLAG=@CLIENTFLAG))
                                     BEGIN
			      rollback transaction  trans_XSCK 
			      set @flagreturn = 0
                                              SET @RETURNSTRING='客户不能为空或客户不存在，单据不能记帐'
                                          RETURN
			END


                       IF @SFLAG=1 and @ClientFLAG=0
                       BEGIN
			      rollback transaction  trans_XSCK 
			      set @flagreturn = 0
                              SET @RETURNSTRING='当客户为供应商的时候，不允许选择现款销售，单据不能记帐'
                              RETURN
		       END



    declare SM_Consign_XSCK Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(UNITPRICE,0)*ISNULL(DISC,0)*0.01 as PRICE, 
                                                                   REDetailBillFlowID,ISNULL(UNITQTY,0) AS UNITQTY  ,PRICETYPE,TAXRATE,JianShu,MeiJianQty,LingTou,REITEMNO  from STOREXSCKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_XSCK

    fetch SM_Consign_XSCK into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY,@PRICETYPE,@TAXRATE,@JianShu,@MeiJianQty,@LingTou,@REITEMNO 

    while @@fetch_status = 0            ----开始
    begin

                     set @MeiJianQty =   (select ISNULL(RATE1,0)  from GOODS where  GOODSID = @GOODSID)


                            IF (ISNULL(@JianShu,0)*ISNULL(@MeiJianQty,0)+ISNULL(@LingTou,0)<>@Unitqty) AND (ISNULL(@JianShu,0)<>0 OR ISNULL(@LingTou,0)<>0)
                                     BEGIN
			      rollback transaction trans_XSCK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='件数*每件数量+零头与数量不等，单据不能记帐'
			    close  SM_Consign_XSCK
			    deallocate  SM_Consign_XSCK
                                          RETURN
			END

            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)  from GOODS where  GOODSID = @GOODSID)

----------------订单处理引用begin

	IF @REITEMNO IS NOT NULL
    BEGIN
	         SELECT   @KEYONGunitQTY = UNITQTY-ISNULL(WCunitQTY,0)   FROM   STOREXSDDD    WHERE  ITEMNO=@REITEMNO
	         SELECT   @KEYONGquantity = quantity-ISNULL(WCquantity,0)   FROM   STOREXSDDD    WHERE  ITEMNO=@REITEMNO
        IF @KEYONGunitQTY >0  or @KEYONGquantity>0
		BEGIN
		   UPDATE   STOREXSDDD   SET WCunitQTY=ISNULL(WCunitQTY,0)+ISNULL(@UNITQTY,0)  WHERE  ITEMNO=@REITEMNO
		   UPDATE   STOREXSDDD   SET WCquantity=ISNULL(WCquantity,0)+ISNULL(@qty,0)  WHERE  ITEMNO=@REITEMNO
		   
			SELECT @TMPunitQTY=SUM(UNITQTY-isnull(WCunitQTY,0))  FROM STOREXSDDD   WHERE  BILLID IN (SELECT BILLID FROM   STOREXSDDD WHERE  ITEMNO=@REITEMNO)
			SELECT @TMPquantity=SUM(quantity-isnull(WCquantity,0))  FROM STOREXSDDD   WHERE  BILLID IN (SELECT BILLID FROM   STOREXSDDD WHERE  ITEMNO=@REITEMNO)
			IF @TMPunitQTY<=0  OR @TMPquantity <= 0
			BEGIN
			   UPDATE   STOREXSDDM   SET STATUS=1  WHERE  BILLID IN (SELECT BILLID FROM   STOREXSDDD WHERE  ITEMNO=@REITEMNO)
			END
		END
		ELSE
		BEGIN
			    set @flagreturn = 0
                SET @RETURNSTRING='引用的订单已经完成或终止，请重新修改单据'
			    close  SM_Consign_XSCK
			    deallocate  SM_Consign_XSCK
			    rollback transaction trans_XSCK
                RETURN
		END
	END

----------------订单处理引用end


---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	


	IF @PRICETYPE=1   
	BEGIN
   	 SELECT @SUMAMT=@SUMAMT+ROUND(@price*@QTY*(1+ISNULL(@TAXRATE,0)*0.01),2)
	END
	IF @PRICETYPE=0  
	BEGIN
   	 SELECT @SUMAMT=@SUMAMT+ROUND(@price*@UNITQTY*(1+ISNULL(@TAXRATE,0)*0.01),2)

		IF   @QTY<>0
		BEGIN
		SET  @PRICE=(@UNITQTY*@PRICE)/@QTY
		END

	END



------------------------------------------

                                        IF NOT (exists (select * from STORE where STOREID=@STOREID))
                                     BEGIN
			      rollback transaction trans_XSCK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close  SM_Consign_XSCK
			    deallocate  SM_Consign_XSCK
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@STOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_XSCK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_XSCK
			    deallocate SM_Consign_XSCK
                                          RETURN
			END




--------------------------------------------
------------更改为数量库存报警
------------
			declare @FuKuCunOUTQty int    ---1代表数量提示，0代表重量提示
			declare @BiJiaoQTY  NUMERIC(20,10)  ---比较过度用的变量


		        set @FuKuCunOUTQty  = (select optionvalue from accoptions where optionname ='FuKuCunOUTQty')     
		
                        IF    @NEGCLOSEOFF=0 
			BEGIN 
				IF @FuKuCunOUTQty=1
				BEGIN 
	                             	EXEC   GETGOODSIDMEQTY  @STOREID,@GOODSID,@YYYYMM,@MEQTY=@STOREIDEQTY   OUTPUT
					SET @BiJiaoQTY=@UNITQTY
				END
				ELSE
				BEGIN 
	                             	EXEC   GETGOODSIDEQTY  @STOREID,@GOODSID,@YYYYMM,@EQTY=@STOREIDEQTY   OUTPUT				
					SET @BiJiaoQTY=@QTY
				END
                                IF @BiJiaoQTY >  ISNULL(@STOREIDEQTY,0)
	                        BEGIN
                     		                  SET  @GOODSNAME =(SELECT code+'  '+NAME+'  '+Specname as GoodsName FROM GOODS WHERE GOODSID=@GOODSID)
				      rollback transaction trans_XSCK
				      set @flagreturn = 0
             		                                 SET @RETURNSTRING='此'+@GOODSNAME+'库存不足不能记帐'
				    close  SM_Consign_XSCK
				    deallocate  SM_Consign_XSCK
	                                          RETURN
				END
			END

--------------------------------------------

            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)

	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE ,@REDetailBillFlowID,  @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',-1,@QTY*@PRICE,null,
	     0,0   )    
--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

                      select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID         -----------反填的是吨价格
	          UPDATE     STOREXSCKD     set    APRICE=@APRICE,  DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_XSCK

--------------------
    fetch SM_Consign_XSCK into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY,@PRICETYPE,@TAXRATE ,@JianShu,@MeiJianQty,@LingTou,@REITEMNO


    END           ------- SM_Consign_XSCK  WHILE

    close SM_Consign_XSCK
    deallocate SM_Consign_XSCK

-------------------
-------------------运费结算开始

          IF  @ChaChePrice<>0
	   begin
		set @YunShuDWID=@ChaCheSID
	            IF   (not exists(select *  from YunShuDWBILLFLOW  where 
             		                                    (rtrim(YunShuDWID) = @YunShuDWID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@YunShuDWID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
	             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@YunShuDWID,
		     0,@ChaCheSYunFei,Null,
		     1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      YunShuDW_CACULATOR_YYYYMM   @YunShuDWID,@YYYYMM

	    end

            IF  @PanYunPrice<>0
	    begin
		set @YunShuDWID=@PanYunSID

	            IF   (not exists(select *  from YunShuDWBILLFLOW  where 
             		                                    (rtrim(YunShuDWID) = @YunShuDWID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@YunShuDWID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
	             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@YunShuDWID,
		     0,@PanYunSYunFei,Null,
		     1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      YunShuDW_CACULATOR_YYYYMM   @YunShuDWID,@YYYYMM

	        end

-------------------运费结算结束
        set @SUMAMT=@SUMAMT+@QiTaFeiYong

        IF @YunFeiZhiFuFX='我方垫付运费' 
        begin
        set @SUMAMT=@SUMAMT+@YunFeiSum
        end


-------------------

	IF @SFLAG=0  and  @ClientFLAG=1
	BEGIN
	            IF   (not exists(select *  from CLIENTBILLFLOW  where 
             		                                    (rtrim(CLIENTID) = @CLIENTID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE, CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode, @CLIENTID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE, CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT ,BuMenID  )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode, @CLIENTID,
		     0,@SUMAMT,Null,
		     1,0, @BuMenID )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM
	END         ---------------IF @SFLAG=0






	IF @SFLAG=0  and  @ClientFLAG=0
	BEGIN

	      SET @VendorID=@ClientID
	            IF   (not exists(select *  from VENDORBILLFLOW  where 
             		                                    (rtrim(VENDORID) = @VENDORID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
	             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,-@SUMAMT,Null,
		     1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM

	END     ----------------     IF @SFLAG=0


----------------------
	IF @SFLAG=1  AND  NOT( @BANKID='APSOFT')
	BEGIN

            IF   (not exists(select *  from BANKBILLFLOW  where 
             		                                    (rtrim(BANKID) = @BANKID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,0,Null,
		     @inoutFlag,0  )    
            END      ------IF   END
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,@SUMAMT,Null,
		     1,0  )    
                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM         update  STOREXSCKM  set  DISCAMT=VendorHKSum           where ltrim(rtrim(BILLID)) = @BILLID 

	END     ----------IF @SFLAG=1

   update  STOREXSCKM  set  flagPost = 1,YYYYMM =@BILLYYYYMM   ,SUMAMT=VendorHKSum ,INVOICEAMT=0          where ltrim(rtrim(BILLID)) = @BILLID 
   update  STOREXSCKD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)          where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STOREXSCKD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)   where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_XSCK
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_XSCK
      set @flagreturn = 0
   end
end
























----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG

















----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[STORE_XSCK_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare  @INF_COSTINGTYPEID  INT
declare  @ClientFlag  INT
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @CLIENTID varchar(10)                   --单句会计年月     
declare @VENDORID varchar(10)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @ChaCheSID VARCHAR(25)
declare @PanYunSID VARCHAR(25)

declare @STOREID    varchar(15)               --明细存货编号
declare @REDetailBillFlowID   varchar(30)                     --序列号
declare @REITEMNO   varchar(30)                     --序列号
declare @QUANTITY   NUMERIC(20,10)                     --序列号
declare @UNITQTY   NUMERIC(20,10)                     --序列号
declare @BILLTYPE   INTEGER
declare @SFLAG   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

                                              SET @RETURNSTRING='   '


	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STOREXSCKM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREXSCKM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_XSCK_DEL   --事物开始

     set @BillType =   (select BillType  from STOREXSCKM where rtrim(BILLID) = @BILLID)

			   IF exists (select * from STOREXSSKD  where REBILLID= @BILLID and rebilltype=2    )
			BEGIN
                                              SET @RETURNSTRING=' 此单据已经被销售收款单引用不能取消记帐！  '
			      rollback transaction trans_XSCK_DEL
			      set @flagreturn = 0
                                         RETURN
			END
			   IF exists (select * from STOREXSFPD  where REBILLID= @BILLID     )
			BEGIN
                              SET @RETURNSTRING=' 此单据已经被销售发票单引用不能取消记帐！  '
			      rollback transaction trans_XSCK_DEL
			      set @flagreturn = 0
                                         RETURN
			END



    declare SM_Consign_XSCK_DEL Cursor for Select GOODSID,DetailBillFlowID,STOREID,REDetailBillFlowID ,QUANTITY,UNITQTY,REITEMNO   from STOREXSCKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_XSCK_DEL

    fetch SM_Consign_XSCK_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@REDetailBillFlowID,@QUANTITY,@UNITQTY,@REITEMNO

    while @@fetch_status = 0            ----开始
    begin

                             DELETE   DetailBillFlow   WHERE  ID=@DetailBillFlowID
       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID
       
----------------订单处理引用begin

	IF @REITEMNO IS NOT NULL
    BEGIN
		   UPDATE   STOREXSDDD   SET WCunitQTY=ISNULL(WCunitQTY,0)-ISNULL(@UNITQTY,0)  WHERE  ITEMNO=@REITEMNO
		   UPDATE   STOREXSDDD   SET WCquantity=ISNULL(WCquantity,0)-ISNULL(@QUANTITY,0)  WHERE  ITEMNO=@REITEMNO
  		   UPDATE   STOREXSDDM   SET STATUS=0  WHERE  BILLID IN (SELECT BILLID FROM   STOREXSDDD WHERE  ITEMNO=@REITEMNO)
	END

----------------订单处理引用end

       
       
       
       
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@STOREID AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
    fetch SM_Consign_XSCK_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@REDetailBillFlowID,@QUANTITY,@UNITQTY,@REITEMNO

    END           ------- SM_Consign_XSCK_DEL  WHILE

    close SM_Consign_XSCK_DEL
    deallocate SM_Consign_XSCK_DEL

		DELETE    DetailBillFlow    WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@billTYPE
------------------------------------以上是删除全部单据明细

	     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREXSCKM where rtrim(BILLID) = @BILLID)
	     set @BANKID =   (select BANKID  from  STOREXSCKM where rtrim(BILLID) = @BILLID)   ---------收款银行
		SELECT @CLIENTID=(SELECT CLIENTID FROM   STOREXSCKM    where ltrim(rtrim(BILLID)) = @BILLID  )
	     set @CLIENTFLAG =   (select  ISNULL(CLIENTFLAG,1)  from STOREXSCKM  where rtrim(BILLID) = @BILLID)



     set @ChaCheSID =   (select ChaCheSID  from STOREXSCKM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @PanYunSID =   (select PanYunSID  from STOREXSCKM where rtrim(BILLID) = @BILLID)   ---------付款银行


		DELETE   YunShuDWBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@BILLTYPE
    		         execute      YunShuDW_CACULATOR_YYYYMM   @ChaCheSID,@YYYYMM
    		         execute      YunShuDW_CACULATOR_YYYYMM   @PanYunSID,@YYYYMM


	IF     @SFLAG=0  and @ClientFlag=1
	BEGIN
		DELETE   CLIENTBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@billTYPE
                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM
	END

		IF @SFLAG=0   and  @ClientFlag=0
		BEGIN

		      SET @VendorID=@ClientID
			DELETE   VENDORBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@BILLTYPE
             		               execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM
	                             DELETE  VENDORBILLFLOW    WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 AND BILLTYPE=@billtype
--------------------------------------以上上全部删除单据  是解决多次记帐失败的问题

		END     


	IF     @SFLAG=1
	BEGIN
		DELETE   BANKBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@billTYPE
                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM
	END


   update  STOREXSCKM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_XSCK_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_XSCK_DEL
      set @flagreturn = 0
   end
end
----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG






----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[STORE_XSDD]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ClientFlag int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ITEMNO varchar(15)               --明细存货编号
declare @YunShuDWID varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号、
declare @CLIENTID varchar(15)               --明细存货编号、
declare @VENDORID varchar(15)               --明细存货编号、
declare @INStoreID varchar(15)               --明细存货编号、
declare @SUMAMT  NUMERIC(20,10)               --明细存货编号、
declare @RATE  NUMERIC(20,10)               --明细存货编号、
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @STOREIDEqty NUMERIC(20,10)                          --仓库数量
declare @REFqty NUMERIC(20,10)                          --数量
declare @UNITqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @PRICETYPE  NUMERIC(20,10)               --含税单价
declare @KEYONGQTY  NUMERIC(20,10)               --含税单价
declare @TAXRATE NUMERIC(20,10)               --含税单价
declare @APRICE  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID  varchar(50)
declare @GOODSNAME varchar(30)                     --序列号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @REITEMNO VARCHAR(25)
declare @BILLDATE DATEtime
declare @SFLAG  INTEGER
declare @YYYYMM_FLAG  INTEGER
declare @count  INTEGER
declare @MaxRate  NUMERIC(20,10)               --含税单价
declare @MinRate  NUMERIC(20,10)               --含税单价
declare @DMinSPrice NUMERIC(20,10)               --含税单价

declare @STOREHSFS   INTEGER
declare @ZhongLiangXZ   INTEGER
declare @XSPriceXZ   INTEGER
declare @NEGCLOSEOFF   bit
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @JianShu [int] 
declare @MeiJianQty [T_QUANTITY] 
declare @LingTou [T_QUANTITY] 

       SELECT    @NEGCLOSEOFF=(SELECT  NEGCLOSEOFF  FROM   ACCINFO    WHERE   GUID='0001' )           

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )  
         


set @BILLID   = ltrim(rtrim(@BILLID))
SET  @RETURNSTRING='  '
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @ZhongLiangXZ   = (select optionvalue from accoptions where optionname ='ZhongLiangXZ')     
     set @XSPriceXZ   = (select optionvalue from accoptions where optionname ='XSPriceXZ')     

     set @BillDate =   (select BillDate  from STOREXSDDM where rtrim(BILLID) = @BILLID)

    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 


      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END


if  (select isnull(flagPost,0) from STOREXSDDM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_XSDD   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREXSDDM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREXSDDM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREXSDDM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREXSDDM where rtrim(BILLID) = @BILLID)
     set @CLIENTID =   (select CLIENTID  from STOREXSDDM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREXSDDM where rtrim(BILLID) = @BILLID)
-----------@SFLAG  是否终止 ，1为终止
-----------@status 订单完成标志
     set @INStoreID =   (select PAYTYPEID  from  STOREXSDDM where rtrim(BILLID) = @BILLID)   ---------收款银行

     set @ClientFLAG =   (select  ISNULL(ClientFLAG,1)   from STOREXSDDM where rtrim(BILLID) = @BILLID)


   	 SELECT @SUMAMT= (SELECT SUM(ROUND(DISC*0.01*unitprice*UNITQTY*(1+ISNULL(TAXRATE,0)*0.01),2)) FROM   STOREXSDDD  where rtrim(BILLID) = @BILLID)
   	 SELECT @SUMAMT=0


           IF NOT (exists (select * from ViewCLIENT where CLIENTID=@CLIENTID   and CLIENTFLAG=@CLIENTFLAG))
            BEGIN
			      rollback transaction  trans_XSDD 
			      set @flagreturn = 0
                  SET @RETURNSTRING='客户不能为空或客户不存在，单据不能记帐'
                  RETURN
			END



   update  STOREXSDDM  set  flagPost = 1,YYYYMM =@BILLYYYYMM   ,SUMAMT=VendorHKSum ,INVOICEAMT=0 ,STATUS=0 ,sflag=0        where ltrim(rtrim(BILLID)) = @BILLID 
   update  STOREXSDDD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0),2)    ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)    where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STOREXSDDD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)     where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_XSDD
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_XSDD
      set @flagreturn = 0
   end
end
----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG






















----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[STORE_XSDD_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare  @INF_COSTINGTYPEID  INT
declare  @ClientFlag  INT
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @CLIENTID varchar(10)                   --单句会计年月     
declare @VENDORID varchar(10)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @ChaCheSID VARCHAR(25)
declare @INSTOREID    varchar(15)               --明细存货编号

declare @STOREID    varchar(15)               --明细存货编号
declare @REDetailBillFlowID   varchar(30)                     --序列号
declare @REITEMNO   varchar(30)                     --序列号
declare @QUANTITY   NUMERIC(20,10)                     --序列号
declare @STATUS INT
declare @UNITQTY   NUMERIC(20,10)                     --序列号
declare @BILLTYPE   INTEGER
declare @SFLAG   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

                                              SET @RETURNSTRING='   '


	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STOREXSDDM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREXSDDM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_XSDD_DEL   --事物开始

     set @BillType =   (select BillType  from STOREXSDDM where rtrim(BILLID) = @BILLID)
     set @INStoreID =   (select PAYTYPEID  from  STOREXSDDM where rtrim(BILLID) = @BILLID)   ---------收款银行
     set @SFLAG =    (select  ISNULL(SFLAG,0)  from STOREXSDDM where rtrim(BILLID) = @BILLID)
	 set @STATUS =   (select  ISNULL(STATUS,0)  from STOREXSDDM where rtrim(BILLID) = @BILLID)

			IF exists(select   ITEMNO   FROM    STOREXSDDD  where rtrim(BILLID) = @BILLID  AND  ITEMNO  IN (SELECT  REITEMNO   FROM    STOREXSCKD ))
			BEGIN
                              SET @RETURNSTRING=' 此订单已经被销售出库单引用不能取消记帐  '
			      rollback transaction trans_XSDD_DEL
			      set @flagreturn = 0
                                         RETURN
			END


			IF  ( @STATUS=1)  OR  (@SFLAG=1)
             		       BEGIN
                            SET @RETURNSTRING=' 此订单已经完成或终止不能取消记帐！'
			      rollback transaction trans_XSDD_DEL
			      set @flagreturn = 0
                           RETURN
			END

			----如果订单已经被引用则不能取消记帐



   update  STOREXSDDM  set  flagPost = 0 ,STATUS=0 ,sflag=0     where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_XSDD_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_XSDD_DEL
      set @flagreturn = 0
   end
end













----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG










CREATE PROCEDURE [dbo].[STORE_XSFP]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---是否现款标志
declare @VENDORFLAG int           ---单据对供应商精确运算标志
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @VENDORID   varchar(15)               --明细存货编号
declare @MakeMan   varchar(15)               --明细存货编号
declare @invoiceCode  varchar(200)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20, 8)                          --数量
declare @SUMAMT NUMERIC(20, 8)                          --单据总金额
declare @REBILLID varchar(15)
declare @REBILLSUMAMT NUMERIC(20,2)                          --引用数量
declare @REBILLDISCAMT NUMERIC(20,2)                          --引用数量
declare @AMT NUMERIC(20,2)                          --引用数量

declare @refqty NUMERIC(20, 8)                          --引用数量
declare @PRICE  NUMERIC(20, 8)               --含税单价
declare @APRICE  NUMERIC(20, 8)               --含税单价
declare @RATE  NUMERIC(20, 8)               --含税单价
declare @BATCHCODE varchar(30)                     --序列号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @UNITID VARCHAR(25)
declare @BILLDATE DATEtime
declare @invoiceDate DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @invoiceFlag  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @PRICEQX   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间


       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

     set @BillDate =   (select BillDate  from STOREXSFPM where rtrim(BILLID) = @BILLID)
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     

      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END

if  (select isnull(flagPost,0) from STOREXSFPM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_XSFP   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREXSFPM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREXSFPM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREXSFPM where rtrim(BILLID) = @BILLID)
     set @MakeMan =   (select MakeMan  from STOREXSFPM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREXSFPM where rtrim(BILLID) = @BILLID)
     set @VENDORID =   (select  VENDOR_CLIENT_ID  from STOREXSFPM where rtrim(BILLID) = @BILLID)
     set @invoiceCode =   (select invoiceCode  from STOREXSFPM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @invoiceDate =   (select invoiceDate  from STOREXSFPM where rtrim(BILLID) = @BILLID)
     set @invoiceFlag =   (select  ISNULL(invoiceFlag,1)  from STOREXSFPM where rtrim(BILLID) = @BILLID)


--------------------------------------------------

----REBILLSUMAMT  单据总额
----REBILLDISCAMT  已开票
----AMT   本次开票

    declare SM_Consign_XSFP Cursor for Select  ITEMNO,REBILLID, REBILLSUMAMT,REBILLDISCAMT,ISNULL(AMT,0) as AMT 
                                                                       from STOREXSFPD where rtrim(BILLID) = @BILLID AND ISNULL(AMT,0)<>0

    Open SM_Consign_XSFP

    fetch SM_Consign_XSFP into @ITEMNO,@REBILLID, @REBILLSUMAMT,@REBILLDISCAMT,@AMT

    while @@fetch_status = 0            ----开始
    begin


	          UPDATE    STOREXSCKM     set    FaPiaoAMT=ISNULL(FaPiaoAMT,0)+@AMT,invoiceCode=ISNULL(invoiceCode,'')+'  '+ISNULL(@invoiceCode,''),
					invoiceDate=@invoiceDate,invoiceFlag=@invoiceFlag
             		           WHERE rtrim(BILLID) = @REBILLID

	  
	          UPDATE    STOREXSCKM     set    STATUS=1
             		           WHERE FaPiaoAMT = SumAMT and YaoPiaoFlag=1


--------------------
    fetch SM_Consign_XSFP into @ITEMNO,@REBILLID, @REBILLSUMAMT,@REBILLDISCAMT,@AMT

    END           ------- SM_Consign_XSFP  WHILE

    close SM_Consign_XSFP
    deallocate SM_Consign_XSFP

-----------------------以上是解决仓库记帐问题，以下是应付帐款的问题
-----------------------------
   update  STOREXSFPM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_XSFP
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_XSFP
      set @flagreturn = 0
   end
end








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG









CREATE PROCEDURE [dbo].[STORE_XSFP_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @invoiceCode varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @BATCHCODE   varchar(30)                     --序列号
declare @VENDORID   varchar(30)                     --序列号
declare @INF_COSTINGTYPEID   INT
declare @VENDORFLAG   INT
declare @AMT NUMERIC(20,2)                          --引用数量
declare @billtype   INT
declare @SFLAG   INT
declare @REFQTY   NUMERIC(20, 8)
declare @STOREHSFS   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @REBILLSUMAMT NUMERIC(20,2)                          --引用数量
declare @REBILLDISCAMT NUMERIC(20,2)                          --引用数量
declare @invoiceDate DATEtime
declare @invoiceFlag  INTEGER
declare @REBILLID varchar(15)
declare @ITEMNO varchar(15)               --明细存货编号

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDate =  (select BILLDate  from STOREXSFPM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
       IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREXSFPM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_XSFP_DEL   --事物开始

	SELECT @VENDORID=VENDOR_CLIENT_ID    FROM STOREXSFPM  where rtrim(BILLID) = @BILLID 
	     set @BillType =   (select BillType  from STOREXSFPM where rtrim(BILLID) = @BILLID)
     set @invoiceCode =   (select invoiceCode  from STOREXSFPM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @invoiceDate =   (select invoiceDate  from STOREXSFPM where rtrim(BILLID) = @BILLID)
     set @invoiceFlag =   (select  ISNULL(invoiceFlag,1)  from STOREXSFPM where rtrim(BILLID) = @BILLID)



    declare SM_Consign_XSFP_DEL Cursor for Select  ITEMNO,REBILLID, REBILLSUMAMT,REBILLDISCAMT,ISNULL(AMT,0) as AMT 
                                                                       from STOREXSFPD where rtrim(BILLID) = @BILLID AND ISNULL(AMT,0)<>0

    Open SM_Consign_XSFP_DEL

    fetch SM_Consign_XSFP_DEL into @ITEMNO,@REBILLID, @REBILLSUMAMT,@REBILLDISCAMT,@AMT

    while @@fetch_status = 0            ----开始
    begin
	          UPDATE    STOREXSCKM     set    FaPiaoAMT=ISNULL(FaPiaoAMT,0)-@AMT,
			invoiceCode=substring(invoiceCode,1,charindex(@invoiceCode,invoiceCode) -1) + 
			substring(invoiceCode,charindex(@invoiceCode,invoiceCode)+ len(@invoiceCode) ,len(invoiceCode)), 
					invoiceDate=NULL,invoiceFlag=@invoiceFlag
             		           WHERE rtrim(BILLID) = @REBILLID
	  

	          UPDATE    STOREXSCKM     set    STATUS=0
             		           WHERE FaPiaoAMT <> SumAMT and YaoPiaoFlag=1
--------------------
    fetch SM_Consign_XSFP_DEL into @ITEMNO,@REBILLID, @REBILLSUMAMT,@REBILLDISCAMT,@AMT

    END           ------- SM_Consign_XSFP_DEL  WHILE

    close SM_Consign_XSFP_DEL
    deallocate SM_Consign_XSFP_DEL

                             DELETE   DetailBillFlow     WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 AND BILLTYPE=@billtype
--------------------------------------以上上全部删除单据  是解决多次记帐失败的问题

   update  STOREXSFPM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_XSFP_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_XSFP_DEL
      set @flagreturn = 0
   end
end








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG










--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[STORE_XSSK]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @REBILLID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @REBILLTYPE int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。


declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)
declare @SFKTYPE int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)

declare @bill_type int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @BANKID varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @CLIENTID   varchar(15)               --明细存货编号
declare @VendorID   varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @BUMENID varchar(15)               --明细存货编号
declare @qty NUMERIC(20, 8)                          --数量
declare @SUMAMT NUMERIC(20, 8)                          --数量
declare @refqty NUMERIC(20, 8)                          --数量
declare @PRICE  NUMERIC(20, 8)               --含税单价
declare @AMT  NUMERIC(20, 8)               --含税单价
declare @MianAMT  NUMERIC(20, 8)               --含税单价




declare @BILLTYPE INTEGER
declare @ClientFLAG INTEGER

declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @MINBILLDATE DATEtime
declare @MAXBILLDATE DATEtime
declare @PRODUCTDATE DATEtime
declare @B_CODE VARCHAR(25)
declare @V_DATE DATEtime
declare @B_ID INTEGER
declare @STOREHSFS   INTEGER
declare @YYYYMM_FLAG  INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

   declare  @PREV_YYYYMM          varchar(6)  -- 上一个会计年月
   declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @BillDate =   (select BillDate  from STOREXSSKM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END



if  (select isnull(flagPost,0) from STOREXSSKM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_XSSK   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREXSSKM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREXSSKM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREXSSKM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREXSSKM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  SFLAG  from STOREXSSKM where rtrim(BILLID) = @BILLID)
     set @CLIENTID =   (select  VENDOR_CLIENT_ID  from STOREXSSKM where rtrim(BILLID) = @BILLID)
     set @SFKTYPE =   (select  isnull(SFKTYPE,0)  from STOREXSSKM where rtrim(BILLID) = @BILLID)
     set @BANKID =   (select  BANKID  from STORExsskM where rtrim(BILLID) = @BILLID)
     set @ClientFLAG =   (select  ISNULL(ClientFLAG,1)   from STOREXSSKM where rtrim(BILLID) = @BILLID)
     set @BuMenID =   (select  BuMenID  from STOREXSSKM where rtrim(BILLID) = @BILLID)


                                      IF NOT (exists (select * from CLIENT where CLIENTID=@CLIENTID))
                                     BEGIN
			      rollback transaction trans_XSSK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='客户不能为空或客户不存在，单据不能记帐'
                                          RETURN
			END

		IF   @SFKTYPE=0
		begin
			      rollback transaction trans_XSSK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='收款类型不能为空，单据不能记帐'
                                          RETURN
		end

		IF  (@ClientFLAG=0) AND  (@SFKTYPE  IN (5,6))   
		begin

			      rollback transaction trans_CGFK
			      set @flagreturn = 0
                              SET @RETURNSTRING='当客户为供应商核算主体时，收款类型只能选择应收账款，否则单据不能记帐！'
                              RETURN
		END



		IF   @SFKTYPE  IN (4,5)    ---@SFKTYPE =6   为不记录
		begin


                                      IF NOT (exists (select * from BANK where BANKID=@BANKID))
                                     BEGIN
			      rollback transaction trans_XSSK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='银行科目不能为空或银行科目不存在，单据不能记帐'
                                          RETURN
			END
		end
   	 SELECT @SUMAMT= (SELECT AMT  FROM  STOREXSSKM   where rtrim(BILLID) = @BILLID)
   	 SELECT @MianAMT= (SELECT ISNULL(MianAMT,0)  FROM  STOREXSSKM   where rtrim(BILLID) = @BILLID)

	IF  @ClientFLAG=1
	BEGIN

	            IF   (not exists(select *  from CLIENTBILLFLOW  where 
             		                                    (rtrim(CLIENTID) = @CLIENTID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@CLIENTID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@CLIENTID,
		     0,@SUMAMT,Null,
		     -1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
		IF @MianAMT <>0
		Begin
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT ,BuMenID  )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode+'免收金额',@CLIENTID,
		     0,@MianAMT,Null,
		     -1,0 ,@BuMenID )    
		END


                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM

		IF   @SFKTYPE  =6    ---@SFKTYPE =6   为不记录
		BEGIN
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@CLIENTID,
		     0,-@SUMAMT,Null,
		     -1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM

		END

	END
	IF @ClientFLAG=0
	BEGIN

	      SET @VendorID=@ClientID
	            IF   (not exists(select *  from VENDORBILLFLOW  where 
             		                                    (rtrim(VENDORID) = @VENDORID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
	             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,@SUMAMT,Null,
		     1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
		IF @MianAMT <>0
		Begin
	             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode+'免收金额',@VENDORID,
		     0,@MianAMT,Null,
		     1,0  )    
               END      ------IF   END
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM

	END     ----------------   	IF @ClientFLAG=0





------------------------------以下是解决科目帐的算法
	IF   @SFKTYPE  IN (4,5)    ---@SFKTYPE =6   为不记录
	begin
	            IF   (not exists(select *  from BANKBILLFLOW  where 
             		                                    (rtrim(BANKID) = @BANKID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,@SUMAMT,Null,
		     1,0  )    
                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM
	end



    declare SM_Consign_XSSK Cursor for Select  REBILLID, isnull(AMT,0)  as amt ,REBILLTYPE   from STOREXSSKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_XSSK

    fetch SM_Consign_XSSK  into @REBILLID,@AMT,@REBILLTYPE

    while @@fetch_status = 0            ----开始
    begin

		IF @REBILLTYPE=2
		BEGIN
		UPDATE   STOREXSCKM   SET DISCAMT= isnull(DISCAMT,0)+@AMT   WHERE BILLID=@REBILLID 
		END
		IF @REBILLTYPE=-3 
		BEGIN
		UPDATE   CLIENT   SET SURAMT= isnull(SURAMT,0)+@AMT   WHERE CLIENTID=@REBILLID 
		END

	    fetch SM_Consign_XSSK  into @REBILLID,@AMT,@REBILLTYPE

    END

    close SM_Consign_XSSK
    deallocate SM_Consign_XSSK



   update  STOREXSSKM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_XSSK
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_XSSK
      set @flagreturn = 0
   end
end







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[STORE_XSSK_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @REBILLID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @BANKID    varchar(15)               --明细存货编号
declare @BATCHCODE   varchar(30)                     --序列号
declare @CLIENTID   varchar(30)                     --序列号
declare @INF_COSTINGTYPEID   INT
declare @REBILLTYPE   INT
declare @REFQTY   NUMERIC(20, 8)
declare @AMT NUMERIC(20, 8)
declare @STOREHSFS   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDate =  (select BILLDate  from STOREXSSKM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
       IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREXSSKM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_XSSK_DEL   --事物开始


	     set @CLIENTID =   (select  VENDOR_CLIENT_ID  from STOREXSSKM where rtrim(BILLID) = @BILLID)

	     set @BANKID =   (select  BANKID  from STOREXSSKM where rtrim(BILLID) = @BILLID)
		DELETE   CLIENTBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=4

                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM

		DELETE   BANKBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=4

                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM

    declare SM_Consign_XSSK_DEL Cursor for Select  REBILLID, isnull(AMT,0)  as amt ,REBILLTYPE   from STOREXSSKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_XSSK_DEL

    fetch SM_Consign_XSSK_DEL  into @REBILLID,@AMT,@REBILLTYPE

    while @@fetch_status = 0            ----开始
    begin

		IF @REBILLTYPE=2
		BEGIN
		UPDATE   STOREXSCKM   SET DISCAMT= isnull(DISCAMT,0)-@AMT   WHERE BILLID=@REBILLID 
		END
		IF @REBILLTYPE=-3 
		BEGIN
		UPDATE   CLIENT   SET SURAMT= isnull(SURAMT,0)-@AMT   WHERE CLIENTID=@REBILLID 
		END

	    fetch SM_Consign_XSSK_DEL  into @REBILLID,@AMT,@REBILLTYPE

    END

    close SM_Consign_XSSK_DEL
    deallocate SM_Consign_XSSK_DEL




   update  STOREXSSKM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_XSSK_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_XSSK_DEL
      set @flagreturn = 0
   end
end





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG

























----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_XSTH]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @BuMenID varchar(10)                   --会计年月     

declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ITEMNO varchar(15)               --明细存货编号
declare @VENDORID varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号、
declare @CLIENTID varchar(15)               --明细存货编号、
declare @SUMAMT  NUMERIC(20,10)               --明细存货编号、
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @INqty NUMERIC(20,10)                          --数量
declare @STOREIDEqty NUMERIC(20,10)                          --仓库数量
declare @REFqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @APRICE  NUMERIC(20,10)               --含税单价
declare @UNITQTY  NUMERIC(20,10)               --含税单价
declare @PRICETYPE  NUMERIC(20,10)               --含税单价
declare @RATE  NUMERIC(20,10)               --含税单价
declare @TAXRATE  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID  varchar(50)
declare @GOODSNAME varchar(30)                     --序列号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BANKID VARCHAR(25)
declare @BILLDATE DATEtime
declare @yyyymm_flag  INTEGER
declare @SFLAG INTEGER
declare @STOREHSFS   INTEGER
declare @NEGCLOSEOFF   bit
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @JianShu [int] 
declare @MeiJianQty [T_QUANTITY] 
declare @LingTou [T_QUANTITY] 

       SELECT    @NEGCLOSEOFF=(SELECT  NEGCLOSEOFF  FROM   ACCINFO    WHERE   GUID='0001' )           

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           


set @BILLID   = ltrim(rtrim(@BILLID))
SET  @RETURNSTRING='  '
   declare  @PREV_YYYYMM          varchar(6)  -- 上一个会计年月
   declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     

     set @BillDate =   (select BillDate  from STOREXSTHM where rtrim(BILLID) = @BILLID)
    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END

if  (select isnull(flagPost,0) from STOREXSTHM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_XSTH   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREXSTHM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREXSTHM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREXSTHM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREXSTHM where rtrim(BILLID) = @BILLID)
     set @CLIENTID =   (select CLIENTID  from STOREXSTHM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREXSTHM where rtrim(BILLID) = @BILLID)
     set @BANKID =   (select BANKID  from  STOREXSTHM where rtrim(BILLID) = @BILLID)   ---------收款银行
     set @BuMenID =   (select BuMenID  from  STOREXSTHM where rtrim(BILLID) = @BILLID)   ---------收款银行


   	 SELECT @SUMAMT= 0



                                      IF NOT (exists (select * from CLIENT where CLIENTID=@CLIENTID))
                                     BEGIN
			      rollback transaction trans_S_SEND
			      set @flagreturn = 0
                                              SET @RETURNSTRING='客户不能为空或客户不存在，单据不能记帐'
                                          RETURN
			END


    declare SM_Consign_XSTH Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(UNITPRICE,0)*ISNULL(DISC,0)*0.01 as PRICE, 
                                                                   REDetailBillFlowID,ISNULL(UNITQTY,0) AS UNITQTY ,PRICETYPE,TAXRATE,JianShu,MeiJianQty,LingTou    from STOREXSTHD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_XSTH

    fetch SM_Consign_XSTH into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY  ,@PRICETYPE,@TAXRATE,@JianShu,@MeiJianQty,@LingTou

    while @@fetch_status = 0            ----开始
    begin

                     set @MeiJianQty =   (select ISNULL(RATE1,0)  from GOODS where  GOODSID = @GOODSID)


                            IF (ISNULL(@JianShu,0)*ISNULL(@MeiJianQty,0)+ISNULL(@LingTou,0)<>@Unitqty) AND (ISNULL(@JianShu,0)<>0 OR ISNULL(@LingTou,0)<>0)
                                     BEGIN
			      rollback transaction trans_XSTH
			      set @flagreturn = 0
                                              SET @RETURNSTRING='件数*每件数量+零头与数量不等，单据不能记帐'
			    close  SM_Consign_XSTH
			    deallocate  SM_Consign_XSTH
                                          RETURN
			END


            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)  from GOODS where  GOODSID = @GOODSID)

---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
        	IF @UNITQTY=0 
		BEGIN
   		 SELECT @UNITQTY=@QTY/@RATE
		END
	END	


	IF @PRICETYPE=1   
	BEGIN
   	 SELECT @SUMAMT=@SUMAMT+ROUND(@price*@QTY*(1+ISNULL(@TAXRATE,0)*0.01),2)
	END
	IF @PRICETYPE=0  
	BEGIN
   	 SELECT @SUMAMT=@SUMAMT+ROUND(@price*@UNITQTY*(1+ISNULL(@TAXRATE,0)*0.01),2)

		IF   @QTY<>0
		BEGIN
		SET  @PRICE=(@UNITQTY*@PRICE)/@QTY
		END

	END

		SELECT @QTY=0-@QTY    ----是负数
                                        IF NOT (exists (select * from STORE where STOREID=@STOREID))
                                     BEGIN
			      rollback transaction trans_XSTH
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close  SM_Consign_XSTH
			    deallocate  SM_Consign_XSTH
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@STOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_XSTH
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_XSTH
			    deallocate SM_Consign_XSTH
                                          RETURN
			END



            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)

	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE  ,@REDetailBillFlowID , @BILLID 



                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT  )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID,-@UNITQTY,
	     @QTY,@price,@StoreID,'F',-1,@QTY*@PRICE,null,
	     0,0 )    
	          UPDATE   STOREXSTHD  set    DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_XSTH

--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END


                      select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID
	          UPDATE     STOREXSTHD     set    APRICE=@APRICE,  DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_XSTH

--------------------
    fetch SM_Consign_XSTH into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY  ,@PRICETYPE,@TAXRATE,@JianShu,@MeiJianQty,@LingTou

    END           ------- SM_Consign_XSTH  WHILE

    close SM_Consign_XSTH
    deallocate SM_Consign_XSTH

   	 SELECT @SUMAMT= 0-@SUMAMT

-------------------
	IF @SFLAG=0
	BEGIN
	            IF   (not exists(select *  from CLIENTBILLFLOW  where 
             		                                    (rtrim(CLIENTID) = @CLIENTID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE, CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode, @CLIENTID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE, CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT ,BuMenID  )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode, @CLIENTID,
		     0,@SUMAMT,Null,
		     1,0  ,@BuMenID)    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM
	END         ---------------IF @SFLAG=0


----------------------
	IF @SFLAG=1  AND  NOT( @BANKID='APSOFT')
	BEGIN

            IF   (not exists(select *  from BANKBILLFLOW  where 
             		                                    (rtrim(BANKID) = @BANKID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,0,Null,
		     @inoutFlag,0  )    
            END      ------IF   END
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,-@SUMAMT,Null,
		     -1,0  )    
                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM
	END     ----------IF @SFLAG=1

   update  STOREXSTHM  set  flagPost = 1,YYYYMM =@BILLYYYYMM , SUMAMT= @SUMAMT ,VendorHKSum=@SUMAMT,INVOICEAMT=0            where ltrim(rtrim(BILLID)) = @BILLID 
---   update  STOREXSCKM  set  flagPost = 1,YYYYMM =@YYYYMM   ,SUMAMT=VendorHKSum ,INVOICEAMT=0          where ltrim(rtrim(BILLID)) = @BILLID 

   update  STOREXSTHD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)          where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STOREXSTHD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)   where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_XSTH
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_XSTH
      set @flagreturn = 0
   end
end












----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_XSTH_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare  @INF_COSTINGTYPEID  INT
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @CLIENTID varchar(10)                   --单句会计年月     
declare @VENDORID varchar(10)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @REDetailBillFlowID   varchar(30)                     --序列号
declare @BANKID  varchar(30)                     --序列号
declare @QUANTITY   NUMERIC(20,10)                     --序列号
declare @REFQTY NUMERIC(20,10)                     --序列号
declare @BILLTYPE   INTEGER
declare @SFLAG   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

                                              SET @RETURNSTRING='   '


	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STOREXSTHM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREXSTHM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_XSTH_DEL   --事物开始

     set @BillType =   (select BillType  from STOREXSTHM where rtrim(BILLID) = @BILLID)

    declare SM_Consign_XSTH_DEL Cursor for Select GOODSID,DetailBillFlowID,STOREID,REDetailBillFlowID ,QUANTITY    from STOREXSTHD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_XSTH_DEL

    fetch SM_Consign_XSTH_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@REDetailBillFlowID,@QUANTITY

    while @@fetch_status = 0            ----开始
    begin

                             DELETE   DetailBillFlow   WHERE  ID=@DetailBillFlowID
       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

--------------------
		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@STOREID AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
        fetch SM_Consign_XSTH_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@REDetailBillFlowID,@QUANTITY

    END           ------- SM_Consign_XSTH_DEL  WHILE

    close SM_Consign_XSTH_DEL
    deallocate SM_Consign_XSTH_DEL

		DELETE    DetailBillFlow    WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@BILLTYPE
------------------------------------以上是删除全部单据明细

	     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREXSTHM where rtrim(BILLID) = @BILLID)
	     set @BANKID =   (select BANKID  from  STOREXSTHM where rtrim(BILLID) = @BILLID)   ---------收款银行
		SELECT @CLIENTID=(SELECT CLIENTID FROM   STOREXSTHM    where ltrim(rtrim(BILLID)) = @BILLID  )

	IF     @SFLAG=0
	BEGIN
		DELETE   CLIENTBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@BILLTYPE
                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM
	END

	IF     @SFLAG=1
	BEGIN
		DELETE   BANKBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@BILLTYPE
                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM
	END




   update  STOREXSTHM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_XSTH_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_XSTH_DEL
      set @flagreturn = 0
   end
end






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_YYYYMM_INSERT]  
                 (
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。

declare @MINBILLDATE DATEtime
declare @MAXBILLDATE DATEtime

declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)

declare @bill_type int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @BILLID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价

declare @yyYY varchar(4)                      --年
declare @mm varchar(2)                      --月
declare @dd varchar(2)                      --日
declare @idm varchar(8)                     --序列号
declare @idd varchar(8)                     --序列号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @B_CODE VARCHAR(25)
declare @V_DATE DATEtime
declare @B_ID INTEGER
declare @STOREHSFS   INTEGER

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
set @BILLID   = ltrim(rtrim(@BILLID))
   declare  @PREV_YYYYMM          varchar(6)  -- 上一个会计年月
   declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     

begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_YYYYMM_INSERT   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       

    declare Cursor_YYYYMM_INSERT Cursor for   SELECT DISTINCT GOODSID, STOREID FROM DETAILBILLFLOW
				WHERE (YYYYMMBILL = 1) AND (YYYYMM =  @YYYYMM) 

    Open Cursor_YYYYMM_INSERT

    fetch Cursor_YYYYMM_INSERT into @GOODSID,@STOREID

    while @@fetch_status = 0            ----开始
    begin

            IF NOT (exists (select * from  DETAILBILLFLOW where  GOODSID=@GOODSID AND  STOREID=@STOREID  AND YYYYMMBILL = 0  AND  YYYYMM =@YYYYMM   ))
            BEGIN


	            EXEC  DetailBillFlow_insert_YYYYMM   '000001' ,@GOODSID ,@STOREID ,0 ,0 ,'000001', '000001' 

	END  -------IF NOT (exists (se

    fetch Cursor_YYYYMM_INSERT into @GOODSID,@STOREID

    END           ------- Cursor_YYYYMM_INSERT  WHILE

    close Cursor_YYYYMM_INSERT
    deallocate Cursor_YYYYMM_INSERT


   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_YYYYMM_INSERT
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_YYYYMM_INSERT
      set @flagreturn = 0
   end
end




----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












--------------------------------------------------------------------
--------------------------------------------------------------------


--------------------------------------------------------------------

CREATE PROCEDURE [STORE_YunFeiFK]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。


declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)

declare @bill_type int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @BANKID varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @VENDORID   varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @DISCAMT NUMERIC(20,10)                          --数量
declare @SUMAMT NUMERIC(20,10)                          --数量
declare @refqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价

declare @BILLTYPE INTEGER

declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @MINBILLDATE DATEtime
declare @MAXBILLDATE DATEtime
declare @PRODUCTDATE DATEtime
declare @B_CODE VARCHAR(25)
declare @V_DATE DATEtime
declare @B_ID INTEGER
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

     set @BillDate =   (select BillDate  from STOREYunFeiFKM where rtrim(BILLID) = @BILLID)

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END



if  (select isnull(flagPost,0) from STOREYunFeiFKM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_YunFeiFK   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREYunFeiFKM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREYunFeiFKM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREYunFeiFKM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  SFLAG  from STOREYunFeiFKM where rtrim(BILLID) = @BILLID)
     set @VENDORID =   (select  VENDORID  from STOREYunFeiFKM where rtrim(BILLID) = @BILLID)
     set @BANKID =   (select  BANKID  from STOREYunFeiFKM where rtrim(BILLID) = @BILLID)


                                      IF NOT (exists (select * from YunShuDW where YunShuDWID=@VENDORID))
                                     BEGIN
			      rollback transaction trans_YunFeiFK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='运输单位不能为空或运输单位不存在，单据不能记帐'
                                          RETURN
			END
	IF   NOT( @BANKID='APSOFT')
	begin
                                      IF NOT (exists (select * from BANK where BANKID=@BANKID))
                                     BEGIN
			      rollback transaction trans_YunFeiFK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='银行科目不能为空或银行科目不存在，单据不能记帐'
                                          RETURN
			END
	end
   	 SELECT @DISCAMT= (SELECT DISCAMT  FROM  STOREYunFeiFKM   where rtrim(BILLID) = @BILLID)
   	 SELECT @SUMAMT= (SELECT ISNULL(SUMAMT,0)  FROM  STOREYunFeiFKM   where rtrim(BILLID) = @BILLID)

            IF   (not exists(select *  from YunShuDWBILLFLOW  where 
             		                                    (rtrim(YunShuDWID) = @VENDORID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN
             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,0,Null,
		     @inoutFlag,0  )    
            END      ------IF   END
             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,@DISCAMT,Null,
		     -1,0  )    

		IF @SUMAMT <>0
		Begin

             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode+'调平金额',@VENDORID,
		     0,@SUMAMT,Null,
		     -1,0  )    
		end
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      YunShuDW_CACULATOR_YYYYMM    @VENDORID,@YYYYMM

------------------------------以下是解决科目帐的算法
	IF   NOT( @BANKID='APSOFT')
	begin

            IF   (not exists(select *  from BANKBILLFLOW  where 
             		                                    (rtrim(BANKID) = @BANKID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,0,Null,
		     @inoutFlag,0  )    
            END      ------IF   END
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,@DISCAMT,Null,
		     -1,0  )    
                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM
	end
   update  STOREYunFeiFKM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_YunFeiFK
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_YunFeiFK
      set @flagreturn = 0
   end
end





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_YunFeiFK_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @BANKID    varchar(15)               --明细存货编号
declare @VENDORID   varchar(30)                     --序列号
declare @INF_COSTINGTYPEID   INT
declare @REFQTY   NUMERIC(20,10)
declare @STOREHSFS   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STOREYunFeiFKM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREYunFeiFKM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_YunFeiFK_DEL   --事物开始


	     set @VENDORID =   (select  VENDORID  from STOREYunFeiFKM where rtrim(BILLID) = @BILLID)

	     set @BANKID =   (select  BANKID  from STOREYunFeiFKM where rtrim(BILLID) = @BILLID)

		DELETE   YunShuDWBILLFLOW   WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=16

                            execute      YunShuDW_CACULATOR_YYYYMM    @VENDORID,@YYYYMM

		DELETE   BANKBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=16

                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM


   update  STOREYunFeiFKM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_YunFeiFK_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_YunFeiFK_DEL
      set @flagreturn = 0
   end
end






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG






















----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_ZCD]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG    int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @GOODSNAME    varchar(50)               --明细存货编号
declare @STOREIDEqty NUMERIC(20,10)                          --仓库数量
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @INSTOREID varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @RATE NUMERIC(20,10)                          --数量
declare @UNITQTY NUMERIC(20,10)                          --数量
declare @REFqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @APRICE  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID  varchar(50)
declare @OUTSTOREID varchar(15)               --明细存货编号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @MINBILLDATE DATEtime
declare @MAXBILLDATE DATEtime
declare @B_ID INTEGER
declare @PRICETYPE INTEGER
declare @COUNT   INTEGER
declare @NEGCLOSEOFF   bit
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @NEGCLOSEOFF=(SELECT  NEGCLOSEOFF  FROM   ACCINFO    WHERE   GUID='0001' )           

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
SET  @RETURNSTRING='  '

set @BILLID   = ltrim(rtrim(@BILLID))


     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @BillDate =   (select BillDate  from  STOREZCDM where rtrim(BILLID) = @BILLID)
    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END


if  (select isnull(flagPost,0) from STOREZCDM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_ZCD   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREZCDM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREZCDM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREZCDM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREZCDM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  SFLAG  from STOREZCDM where rtrim(BILLID) = @BILLID)
---     set @INSTOREID  =  (select  VENDORID  from STOREZCDM where rtrim(BILLID) = @BILLID)
--     set @OUTSTOREID  =  (select CLIENTID  from STOREZCDM where rtrim(BILLID) = @BILLID)


    declare SM_Consign_ZCDOUT Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(PRICE,0) as PRICE, 
                                                                   REDetailBillFlowID,Isnull(UNITQTY,0) as UNITQTY,PRICETYPE   from STOREZCDD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_ZCDOUT

    fetch SM_Consign_ZCDOUT into @ITEMNO,@GOODSID,@OUTSTOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY ,@PRICETYPE   

    while @@fetch_status = 0            ----开始
    begin
                                      IF NOT (exists (select * from STORE where STOREID=@OUTSTOREID))
                                     BEGIN
			      rollback transaction trans_ZCD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close SM_Consign_ZCDOUT
			    deallocate SM_Consign_ZCDOUT
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@OUTSTOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_ZCD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_ZCDOUT
			    deallocate SM_Consign_ZCDOUT
                                          RETURN
			END


			declare @FuKuCunOUTQty int    ---1代表数量提示，0代表重量提示
			declare @BiJiaoQTY  NUMERIC(20,10)  ---比较过度用的变量


		        set @FuKuCunOUTQty  = (select optionvalue from accoptions where optionname ='FuKuCunOUTQty')     
		
                        IF    @NEGCLOSEOFF=0 
			BEGIN 
				IF @FuKuCunOUTQty=1
				BEGIN 
	                             	EXEC   GETGOODSIDMEQTY  @OUTSTOREID,@GOODSID,@YYYYMM,@MEQTY=@STOREIDEQTY   OUTPUT
					SET @BiJiaoQTY=@UNITQTY
				END
				ELSE
				BEGIN 
	                             	EXEC   GETGOODSIDEQTY  @OUTSTOREID,@GOODSID,@YYYYMM,@EQTY=@STOREIDEQTY   OUTPUT				
					SET @BiJiaoQTY=@QTY
				END
                                IF @BiJiaoQTY >  ISNULL(@STOREIDEQTY,0)
 		                        BEGIN
                          		                  SET  @GOODSNAME =(SELECT NAME  FROM GOODS WHERE GOODSID=@GOODSID)
				      rollback transaction trans_ZCD
				      set @flagreturn = 0
             		                                 SET @RETURNSTRING='此'+@GOODSNAME+'库存不足不能记帐'
				    close SM_Consign_ZCDOUT
				    deallocate SM_Consign_ZCDOUT
                          		                RETURN
				END
			END
            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)  from GOODS where  GOODSID = @GOODSID)


---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	



	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@OUTSTOREID ,@qty ,@PRICE ,@REDetailBillFlowID, @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output

	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT)
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     -@QTY,@price,@OUTStoreID,'F',-1,@QTY*@PRICE,null, 
	    0,0 )    
--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格


                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@OUTSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@OUTSTOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@OUTSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@OUTSTOREID,@YYYYMM
				     END

                            END




-------------------其实三种成本价的核算方式都一样  
--------反填成本单价
		IF   @SFLAG=0   --------反填
		BEGIN
			IF @PRICETYPE=1    ----吨
			BEGIN
		                      select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID
			          UPDATE   STOREZCDD  set  UNITPRICE=@APRICE
             			           WHERE CURRENT OF   SM_Consign_ZCDOUT
			END
			IF @PRICETYPE=0    ----数量
			BEGIN
		                      select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID
			          UPDATE   STOREZCDD  set  UNITPRICE=@APRICE*@QTY/@UNITQTY
             			           WHERE CURRENT OF   SM_Consign_ZCDOUT
			END
		
		END

                  
--------------------
    fetch SM_Consign_ZCDOUT into @ITEMNO,@GOODSID,@OUTSTOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY ,@PRICETYPE   

    END           ------- SM_Consign_ZCDOUT  WHILE

    close SM_Consign_ZCDOUT
    deallocate SM_Consign_ZCDOUT


-----------------------------------------------------以上是出库，以下是入库

    declare SM_Consign_ZCDIN Cursor for Select  ITEMNO,GOODSID,INSTOREID,isnull(QUANTITY,0) as qty,isnull(PRICE,0) as PRICE, 
                                                                   REDetailBillFlowID ,UNITQTY ,PRICETYPE   from STOREZCDD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_ZCDIN

    fetch SM_Consign_ZCDIN into @ITEMNO,@GOODSID,@INSTOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY  ,@PRICETYPE

    while @@fetch_status = 0            ----开始
    begin
                                      IF NOT (exists (select * from STORE where STOREID=@INSTOREID))
                                     BEGIN
			      rollback transaction trans_ZCD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close SM_Consign_ZCDIN
			    deallocate SM_Consign_ZCDIN
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@INSTOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_ZCD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_ZCDIN
			    deallocate SM_Consign_ZCDIN
                                          RETURN
			END



            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)  from GOODS where  GOODSID = @GOODSID)


---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	


	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@INSTOREID ,@qty ,@PRICE ,@REDetailBillFlowID,  @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output

	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID, MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@INStoreID,'F',1,@QTY*@PRICE,null,
	    0,0)    

	          UPDATE   STOREZCDD  set    DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_ZCDIN
-----------====================2012-09-04 begin

	IF   @INF_COSTINGTYPEID=6 
	Begin

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output

	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID, MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,2,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@INStoreID,'F',1,@QTY*@PRICE,null,
	    0,0)    
	end
--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格

                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@INSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@INSTOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@INSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@INSTOREID,@YYYYMM
				     END

                            END



		IF   @SFLAG=0   --------反填
		BEGIN
			IF @PRICETYPE=1    ----吨
			BEGIN
		                      select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID
			          UPDATE   STOREZCDD  set  UNITPRICE=@APRICE
             			           WHERE CURRENT OF   SM_Consign_ZCDIN
			END
			IF @PRICETYPE=0    ----数量
			BEGIN
		                      select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID
			          UPDATE   STOREZCDD  set  UNITPRICE=@APRICE*@QTY/@UNITQTY
             			           WHERE CURRENT OF   SM_Consign_ZCDIN
			END
		
		END

    fetch SM_Consign_ZCDIN into @ITEMNO,@GOODSID,@INSTOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY  ,@PRICETYPE

    END           ------- SM_Consign_ZCDIN  WHILE

    close SM_Consign_ZCDIN
    deallocate SM_Consign_ZCDIN


   update  STOREZCDM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
   update  STOREZCDD  set   AMT  =  Round(ISNULL(quantity,0)*ISNULL(UNITprice,0),2)               where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STOREZCDD  set   AMT  =  Round(ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)            where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_ZCD
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_ZCD
      set @flagreturn = 0
   end
end








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG

















--------------------------------------------------------------------
----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_ZCD_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   

                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --会计年月   
DECLARE @DetailBillFlowID  varchar(8)                   --会计年月   
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @STOREID    varchar(15)               --明细存货编号
declare @REFQTY   NUMERIC(20,10)

declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)

declare @bill_type int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @INSTOREID varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @QUANTITY NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID  varchar(50)
declare @OUTSTOREID varchar(15)               --明细存货编号

declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @B_CODE VARCHAR(25)
declare @PRODUCTDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           


                                              SET @RETURNSTRING='   '


set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STOREZCDM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREZCDM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_ZCD_DEL   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREZCDM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREZCDM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREZCDM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREZCDM where rtrim(BILLID) = @BILLID)
--     set @INSTOREID  =  (select CLIENTID  from STOREZCDM where rtrim(BILLID) = @BILLID)
--     set @OUTSTOREID  =  (select VENDORID  from STOREZCDM where rtrim(BILLID) = @BILLID)

    declare SM_Consign_ZCDOUT_DEL Cursor for Select  ITEMNO,GOODSID,STOREID,INSTOREID,REDetailBillFlowID ,QUANTITY ,DetailBillFlowID   from STOREZCDD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_ZCDOUT_DEL

    fetch SM_Consign_ZCDOUT_DEL into @ITEMNO,@GOODSID,@OUTSTOREID,@INSTOREID,@REDetailBillFlowID ,@QUANTITY,@DetailBillFlowID

    while @@fetch_status = 0            ----开始
    begin
	            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
             		  DELETE    DetailBillFlow    WHERE ITEMNO=@ITEMNO  AND BILLID=@BILLID  AND GOODSID=@GOODSID  AND BILLTYPE=205

                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@OUTSTOREID,@YYYYMM
	                             execute      APRICECACULATOR_STORE   @GOODSID,@INSTOREID,@YYYYMM
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@OUTSTOREID,@YYYYMM
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@INSTOREID,@YYYYMM
                            END


                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@OUTSTOREID,@YYYYMM
	                             execute      APRICECACULATOR_STORE   @GOODSID,@INSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
	                             execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@OUTSTOREID,@YYYYMM
	                             execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@INSTOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@OUTSTOREID,@YYYYMM
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@INSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
             		                execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@OUTSTOREID,@YYYYMM
             		                execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@INSTOREID,@YYYYMM
				     END

                            END


		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@OUTSTOREID  AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@INSTOREID  AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM

	    fetch SM_Consign_ZCDOUT_DEL into @ITEMNO,@GOODSID,@OUTSTOREID,@INSTOREID,@REDetailBillFlowID ,@QUANTITY,@DetailBillFlowID

    END           ------- SM_Consign_ZCDOUT  WHILE

    close SM_Consign_ZCDOUT_DEL
    deallocate SM_Consign_ZCDOUT_DEL



   update  STOREZCDM  set  flagPost = 0      where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_ZCD_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_ZCD_DEL
      set @flagreturn = 0
   end
end





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG




































----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_ZFD]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @BuMenID varchar(10)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ClientFlag int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ITEMNO varchar(15)               --明细存货编号
declare @YunShuDWID varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号、
declare @CLIENTID varchar(15)               --明细存货编号、
declare @VENDORID varchar(15)               --明细存货编号、
declare @BANKID varchar(15)               --明细存货编号、
declare @SUMAMT  NUMERIC(20,10)               --明细存货编号、
declare @RATE  NUMERIC(20,10)               --明细存货编号、
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @STOREIDEqty NUMERIC(20,10)                          --仓库数量
declare @REFqty NUMERIC(20,10)                          --数量
declare @UNITqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @PRICETYPE  NUMERIC(20,10)               --含税单价
declare @KEYONGQTY  NUMERIC(20,10)               --含税单价
declare @TAXRATE NUMERIC(20,10)               --含税单价
declare @APRICE  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID  varchar(50)
declare @GOODSNAME varchar(30)                     --序列号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @REITEMNO VARCHAR(25)
declare @BILLDATE DATEtime
declare @SFLAG  INTEGER
declare @YYYYMM_FLAG  INTEGER
declare @count  INTEGER
declare @ChaCheSID VARCHAR(25)
declare @PanYunSID VARCHAR(25)
declare @YunFeiZhiFuFX VARCHAR(25)  ----运费支付方向
declare @ChaChePrice  NUMERIC(20,10)               --含税单价
declare @PanYunPrice  NUMERIC(20,10)               --含税单价
declare @ChaCheSYunfei  NUMERIC(20,10)               --含税单价
declare @PanYunSYunfei  NUMERIC(20,10)               --含税单价
declare @QiTaFeiYong  NUMERIC(20,10)               --含税单价
declare @YunFeiSum  NUMERIC(20,10)               --含税单价
declare @MaxRate  NUMERIC(20,10)               --含税单价
declare @MinRate  NUMERIC(20,10)               --含税单价
declare @DMinSPrice NUMERIC(20,10)               --含税单价

declare @STOREHSFS   INTEGER
declare @ZhongLiangXZ   INTEGER
declare @XSPriceXZ   INTEGER
declare @NEGCLOSEOFF   bit
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @JianShu [int] 
declare @MeiJianQty [T_QUANTITY] 
declare @LingTou [T_QUANTITY] 


       SELECT    @NEGCLOSEOFF=(SELECT  NEGCLOSEOFF  FROM   ACCINFO    WHERE   GUID='0001' )           

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )  
         


set @BILLID   = ltrim(rtrim(@BILLID))
SET  @RETURNSTRING='  '
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @ZhongLiangXZ   = (select optionvalue from accoptions where optionname ='ZhongLiangXZ')     
     set @XSPriceXZ   = (select optionvalue from accoptions where optionname ='XSPriceXZ')     

     set @BillDate =   (select BillDate  from STOREZFDM where rtrim(BILLID) = @BILLID)

    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 


      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END


if  (select isnull(flagPost,0) from STOREZFDM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_ZFD   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREZFDM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREZFDM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREZFDM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREZFDM where rtrim(BILLID) = @BILLID)
     set @CLIENTID =   (select CLIENTID  from STOREZFDM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREZFDM where rtrim(BILLID) = @BILLID)
     set @ClientFLAG =   (select  ISNULL(ClientFLAG,1)   from STOREZFDM where rtrim(BILLID) = @BILLID)
     set @BANKID =   (select BANKID  from  STOREZFDM where rtrim(BILLID) = @BILLID)   ---------收款银行
     set @BuMenID =   (select BuMenID  from  STOREZFDM where rtrim(BILLID) = @BILLID)   ---------收款银行

     set @ChaCheSID =   (select ChaCheSID  from STOREZFDM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @PanYunSID =   (select PanYunSID  from STOREZFDM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @YunFeiZhiFuFX =   (select YunFeiZhiFuFX  from STOREZFDM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @ChaChePrice =   (select ISNULL(ChaChePrice,0)  from STOREZFDM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @PanYunPrice =   (select ISNULL(PanYunPrice,0)  from STOREZFDM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @ChaCheSYunFei=    (select ROUND(ISNULL(ChaChePrice,0)*SumQUANTITY,2) from STOREZFDM where rtrim(BILLID) = @BILLID)   ---------付款银行 
     set @PanYunSYunFei=    (select ROUND(ISNULL(PanYunPrice,0)*SumQUANTITY,2) from STOREZFDM where rtrim(BILLID) = @BILLID)   ---------付款银行 
     set @YunFeiSum=   @ChaCheSYunFei+@PanYunSYunFei
     set @QiTaFeiYong =   (select ISNULL(QiTaFeiYong,0)  from STOREZFDM where rtrim(BILLID) = @BILLID)   ---------付款银行


   	 SELECT @SUMAMT= (SELECT SUM(ROUND(DISC*0.01*unitprice*UNITQTY*(1+ISNULL(TAXRATE,0)*0.01),2)) FROM   STOREZFDD  where rtrim(BILLID) = @BILLID)
   	 SELECT @SUMAMT=0

                              IF (NOT exists(select * from YunShuDW where YunShuDWID=@ChaCheSID)) and @ChaChePrice<>0
                              BEGIN
			      rollback transaction trans_CGRK
			      set @flagreturn = 0
                                      SET @RETURNSTRING='叉车商不能为空或叉车商不存在，单据不能记帐'
                                       RETURN
			END

                              IF (NOT exists(select * from YunShuDW where YunShuDWID=@PanYunSID)) and @PanYunPrice<>0
                              BEGIN
			      rollback transaction trans_CGRK
			      set @flagreturn = 0
                                      SET @RETURNSTRING='盘运商不能为空或盘运商不存在，单据不能记帐'
                                       RETURN
			END

                                      IF NOT (exists (select * from ViewCLIENT where CLIENTID=@CLIENTID   and CLIENTFLAG=@CLIENTFLAG))
                                     BEGIN
			      rollback transaction  trans_ZFD 
			      set @flagreturn = 0
                                              SET @RETURNSTRING='客户不能为空或客户不存在，单据不能记帐'
                                          RETURN
			END


                       IF @SFLAG=1 and @ClientFLAG=0
                       BEGIN
			      rollback transaction  trans_ZFD 
			      set @flagreturn = 0
                              SET @RETURNSTRING='当客户为供应商的时候，不允许选择现款销售，单据不能记帐'
                              RETURN
		       END



    declare SM_Consign_ZFD Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(UNITPRICE,0)*ISNULL(DISC,0)*0.01 as PRICE, 
                                                                   REDetailBillFlowID,ISNULL(UNITQTY,0) AS UNITQTY  ,PRICETYPE,TAXRATE,JianShu,MeiJianQty,LingTou  from STOREZFDD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_ZFD

    fetch SM_Consign_ZFD into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY,@PRICETYPE,@TAXRATE,@JianShu,@MeiJianQty,@LingTou 

    while @@fetch_status = 0            ----开始
    begin

                     set @MeiJianQty =   (select ISNULL(RATE1,0)  from GOODS where  GOODSID = @GOODSID)


                            IF (ISNULL(@JianShu,0)*ISNULL(@MeiJianQty,0)+ISNULL(@LingTou,0)<>@Unitqty) AND (ISNULL(@JianShu,0)<>0 OR ISNULL(@LingTou,0)<>0)
                                     BEGIN
			      rollback transaction trans_ZFD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='件数*每件数量+零头与数量不等，单据不能记帐'
			    close  SM_Consign_ZFD
			    deallocate  SM_Consign_ZFD
                                          RETURN
			END


    fetch SM_Consign_ZFD into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY,@PRICETYPE,@TAXRATE ,@JianShu,@MeiJianQty,@LingTou


    END           ------- SM_Consign_ZFD  WHILE

    close SM_Consign_ZFD
    deallocate SM_Consign_ZFD

-------------------
-------------------运费结算开始

          IF  @ChaChePrice<>0
	   begin
		set @YunShuDWID=@ChaCheSID
	            IF   (not exists(select *  from YunShuDWBILLFLOW  where 
             		                                    (rtrim(YunShuDWID) = @YunShuDWID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@YunShuDWID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
	             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@YunShuDWID,
		     0,@ChaCheSYunFei,Null,
		     1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      YunShuDW_CACULATOR_YYYYMM   @YunShuDWID,@YYYYMM

	    end

            IF  @PanYunPrice<>0
	    begin
		set @YunShuDWID=@PanYunSID

	            IF   (not exists(select *  from YunShuDWBILLFLOW  where 
             		                                    (rtrim(YunShuDWID) = @YunShuDWID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@YunShuDWID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
	             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@YunShuDWID,
		     0,@PanYunSYunFei,Null,
		     1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      YunShuDW_CACULATOR_YYYYMM   @YunShuDWID,@YYYYMM

	        end

-------------------运费结算结束
        set @SUMAMT=@SUMAMT+@QiTaFeiYong

        IF @YunFeiZhiFuFX='我方垫付运费' 
        begin
        set @SUMAMT=@SUMAMT+@YunFeiSum
        end


-------------------

	IF @SFLAG=0  and  @ClientFLAG=1
	BEGIN
	            IF   (not exists(select *  from CLIENTBILLFLOW  where 
             		                                    (rtrim(CLIENTID) = @CLIENTID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE, CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode, @CLIENTID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE, CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT ,BuMenID  )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode, @CLIENTID,
		     0,@SUMAMT,Null,
		     1,0, @BuMenID )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM
	END         ---------------IF @SFLAG=0






	IF @SFLAG=0  and  @ClientFLAG=0
	BEGIN

	      SET @VendorID=@ClientID
	            IF   (not exists(select *  from VENDORBILLFLOW  where 
             		                                    (rtrim(VENDORID) = @VENDORID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
	             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,-@SUMAMT,Null,
		     1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM

	END     ----------------     IF @SFLAG=0


----------------------
   update  STOREZFDM  set  flagPost = 1,YYYYMM =@BILLYYYYMM   ,SUMAMT=VendorHKSum ,INVOICEAMT=0          where ltrim(rtrim(BILLID)) = @BILLID 
   update  STOREZFDD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)          where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STOREZFDD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)   where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_ZFD
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_ZFD
      set @flagreturn = 0
   end
end
























----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG



















----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_ZFD_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare  @INF_COSTINGTYPEID  INT
declare  @ClientFlag  INT
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @CLIENTID varchar(10)                   --单句会计年月     
declare @VENDORID varchar(10)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @ChaCheSID VARCHAR(25)
declare @PanYunSID VARCHAR(25)

declare @STOREID    varchar(15)               --明细存货编号
declare @REDetailBillFlowID   varchar(30)                     --序列号
declare @REITEMNO   varchar(30)                     --序列号
declare @QUANTITY   NUMERIC(20,10)                     --序列号
declare @UNITQTY   NUMERIC(20,10)                     --序列号
declare @BILLTYPE   INTEGER
declare @SFLAG   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

                                              SET @RETURNSTRING='   '


	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STOREZFDM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREZFDM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_ZFD_DEL   --事物开始

     set @BillType =   (select BillType  from STOREZFDM where rtrim(BILLID) = @BILLID)



	     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREZFDM where rtrim(BILLID) = @BILLID)
	     set @BANKID =   (select BANKID  from  STOREZFDM where rtrim(BILLID) = @BILLID)   ---------收款银行
		SELECT @CLIENTID=(SELECT CLIENTID FROM   STOREZFDM    where ltrim(rtrim(BILLID)) = @BILLID  )
	     set @CLIENTFLAG =   (select  ISNULL(CLIENTFLAG,1)  from STOREZFDM  where rtrim(BILLID) = @BILLID)



     set @ChaCheSID =   (select ChaCheSID  from STOREZFDM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @PanYunSID =   (select PanYunSID  from STOREZFDM where rtrim(BILLID) = @BILLID)   ---------付款银行


		DELETE   YunShuDWBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@BILLTYPE
    		         execute      YunShuDW_CACULATOR_YYYYMM   @ChaCheSID,@YYYYMM
    		         execute      YunShuDW_CACULATOR_YYYYMM   @PanYunSID,@YYYYMM


	IF     @SFLAG=0  and @ClientFlag=1
	BEGIN
		DELETE   CLIENTBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@billTYPE
                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM
	END

		IF @SFLAG=0   and  @ClientFlag=0
		BEGIN

		      SET @VendorID=@ClientID
			DELETE   VENDORBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@BILLTYPE
             		               execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM
	                             DELETE  VENDORBILLFLOW    WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 AND BILLTYPE=@billtype
--------------------------------------以上上全部删除单据  是解决多次记帐失败的问题

		END     




   update  STOREZFDM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_ZFD_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_ZFD_DEL
      set @flagreturn = 0
   end
end










----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG




















--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[Store_Yue_JiSuan]
as



Declare 
        @end_dateAddone  datetime,
        @YYYYMM  varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @WHERESTING   varchar(1800),
        @STOREIDSTR   varchar(100),
        @DBSTING   varchar(100)

--@WHERESTR='  and 1=1 '
			SELECT    @WHERESTING  ='     '

			SELECT    @STOREIDSTR   = '     '

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     

----------------------------------------------------


                delete Store_GoodsID_YUE
----------------------------------------------------
		SELECT @SQLSTR='	 select  I.GOODSID,       '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)+ isnull(E.INQTY,0)  as EQTY, '   --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0)  as UNITQTY '   --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from Goods  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(INQTY*INOUTFLAG)  as INQTY  ,sum(MINQTY*INOUTFLAG)  as MINQTY '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)  +@STOREIDSTR                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(BQTY) as BQTY ,sum(MBQTY) as MBQTY '
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) +@STOREIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where     I. GOODSID in (select GOODSID from DETAILBILLFLOW where YYYYMM >='+char(39)+@YYYYMM+char(39)+@STOREIDSTR+')'  + @WHERESTING 
		SELECT @SQLSTR=@SQLSTR+'          order by  I.CODE                '

		INSERT INTO  Store_GoodsID_YUE  EXEC(@SQLSTR)

















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG










CREATE PROCEDURE [dbo].[UPDATE_DATA]      --APSOFTENCRYPTION       WITH ENCRYPTION
AS 


BEGIN

declare   @MAXID    varchar(10)

	       UPDATE   GOODS         SET INF_COSTINGTYPEID=1  WHERE    INF_COSTINGTYPEID NOT IN ( 1,2,3,4,5,6)

-----		SELECT  @MAXID=MAX(GOODSID)  FROM GOODS  where Len(GoodsID)=8  and substring(GoodsID,1,3)='000'

--------       UPDATE  KEYVALUETABLE   SET KEYVALUE=@MAXID WHERE   TABLENAME= 'GOODS'  

		declare @flagreturn int 
		exec STORE_YYYYMM_INSERT   @flagreturn output 

	       UPDATE   CLIENT         SET BEGINAMOUNT =0  WHERE   BEGINAMOUNT IS NULL
	       UPDATE   CLIENTBILLFLOW         SET BAMOUNT =0  WHERE  BAMOUNT IS NULL
	       UPDATE   CLIENTBILLFLOW         SET INAMOUNT =0  WHERE  INAMOUNT IS NULL
	       UPDATE   CLIENTBILLFLOW         SET OUTAMOUNT =0  WHERE  OUTAMOUNT IS NULL
	       UPDATE   CLIENTBILLFLOW         SET EAMOUNT =0  WHERE  EAMOUNT IS NULL

	       UPDATE   DETAILBILLFLOW         SET BQTY =0  WHERE  BQTY IS NULL
	       UPDATE   DETAILBILLFLOW         SET BPRICE =0  WHERE  BPRICE  IS NULL
	       UPDATE   DETAILBILLFLOW         SET BAMOUNT =0  WHERE  BAMOUNT IS NULL
	       UPDATE   DETAILBILLFLOW         SET INQTY =0  WHERE  INQTY IS NULL
	       UPDATE   DETAILBILLFLOW         SET INPRICE =0  WHERE  INPRICE  IS NULL
	       UPDATE   DETAILBILLFLOW         SET OUTQTY =0  WHERE  OUTQTY IS NULL
	       UPDATE   DETAILBILLFLOW         SET OUTPRICE =0  WHERE   OUTPRICE  IS NULL
	       UPDATE   DETAILBILLFLOW         SET EQTY =0  WHERE  EQTY IS NULL
	       UPDATE   DETAILBILLFLOW         SET EPRICE =0  WHERE  EPRICE  IS NULL
	       UPDATE   DETAILBILLFLOW         SET EAMOUNT =0  WHERE  EAMOUNT IS NULL

	       UPDATE   DETAILBILLFLOW         SET STOREEQTY =0  WHERE  STOREEQTY IS NULL
	       UPDATE   DETAILBILLFLOW         SET STOREEPRICE =0  WHERE  STOREEPRICE  IS NULL
	       UPDATE   DETAILBILLFLOW         SET STOREEAMOUNT =0  WHERE  STOREEAMOUNT IS NULL

	       UPDATE   DETAILBILLFLOW         SET REFQTY =0  WHERE REFQTY IS NULL
	       UPDATE   DETAILBILLFLOW         SET REFCOUNT =0  WHERE  REFCOUNT  IS NULL

	       UPDATE   GOODSINIT           SET BQTY =0  WHERE  BQTY IS NULL
	       UPDATE   GOODSINIT           SET BPRICE =0  WHERE  BPRICE  IS NULL
	       UPDATE   GOODSINIT           SET BAMOUNT =0  WHERE  BAMOUNT IS NULL
	       UPDATE   GOODSINIT           SET INQTY =0  WHERE  INQTY IS NULL
	       UPDATE   GOODSINIT           SET OUTQTY =0  WHERE  OUTQTY IS NULL
	       UPDATE   GOODSINIT           SET EQTY =0  WHERE  EQTY IS NULL
	       UPDATE   GOODSINIT           SET EPRICE =0  WHERE  EPRICE  IS NULL
	       UPDATE   GOODSINIT           SET EAMOUNT =0  WHERE  EAMOUNT IS NULL

	       UPDATE   STORECGFKM          SET DISCAMT =0  WHERE  DISCAMT  IS NULL
	       UPDATE   STORECGFKM          SET FLAGPOST =0  WHERE  FLAGPOST  IS NULL
	       UPDATE   STORECGFKM          SET INOUTFLAG =-1  WHERE  INOUTFLAG  IS NULL

	       UPDATE   STORECGRKM          SET FLAGPOST =0  WHERE  FLAGPOST  IS NULL
	       UPDATE   STORECGRKM          SET INOUTFLAG =1  WHERE  INOUTFLAG  IS NULL

	       UPDATE   STORECGRKD         SET APRICE =0  WHERE  APRICE  IS NULL
	       UPDATE   STORECGRKD          SET PRICE =0  WHERE  PRICE  IS NULL
	       UPDATE   STORECGRKD          SET QUANTITY =0  WHERE  QUANTITY  IS NULL
	       UPDATE   STORECGRKD          SET TAXRATE =0  WHERE  TAXRATE  IS NULL

	DELETE   VENDORBILLFLOW  WHERE   YYYYMMBILL=1 AND  BILLTYPE=8 AND  (BILLID NOT IN (SELECT BILLID FROM STORECGFKM) )
	DELETE   BANKBILLFLOW  WHERE   YYYYMMBILL=1 AND  BILLTYPE=8 AND  (BILLID NOT IN (SELECT BILLID FROM STORECGFKM) )

	DELETE DetailBillFlow  WHERE   YYYYMMBILL=1  AND  BILLTYPE=1 AND  (BILLID NOT IN (SELECT BILLID FROM STORECGRKM) )
	DELETE VENDORBILLFLOW  WHERE   YYYYMMBILL=1 AND  BILLTYPE=1 AND  (BILLID NOT IN (SELECT BILLID FROM STORECGRKM) )
	DELETE BANKBILLFLOW    WHERE   YYYYMMBILL=1 AND  BILLTYPE=1 AND  (BILLID NOT IN (SELECT BILLID FROM STORECGRKM) )
	DELETE YunShuDWBILLFLOW    WHERE   YYYYMMBILL=1 AND  BILLTYPE=1 AND  (BILLID NOT IN (SELECT BILLID FROM STORECGRKM) )


	DELETE DetailBillFlow  WHERE   YYYYMMBILL=1  AND  BILLTYPE=7 AND  (BILLID NOT IN (SELECT BILLID FROM STORECGTHM) )
	DELETE VENDORBILLFLOW  WHERE   YYYYMMBILL=1 AND  BILLTYPE=7 AND  (BILLID NOT IN (SELECT BILLID FROM STORECGTHM) )
	DELETE BANKBILLFLOW    WHERE   YYYYMMBILL=1 AND  BILLTYPE=7 AND  (BILLID NOT IN (SELECT BILLID FROM STORECGTHM) )

	DELETE DetailBillFlow  WHERE   YYYYMMBILL=1  AND  BILLTYPE=5 AND  (BILLID NOT IN (SELECT BILLID FROM STORECKDBM) )

	DELETE DetailBillFlow  WHERE   YYYYMMBILL=1  AND  BILLTYPE=6 AND  (BILLID NOT IN (SELECT BILLID FROM STORECKPDM) )

	DELETE BANKBILLFLOW    WHERE   YYYYMMBILL=1 AND  BILLTYPE=13 AND  (BILLID NOT IN (SELECT BILLID FROM STOREFYKZM) )
	DELETE DetailBillFlow  WHERE   YYYYMMBILL=1  AND  BILLTYPE=213 AND  (BILLID NOT IN (SELECT BILLID FROM STOREGJRKM) )

	DELETE BANKBILLFLOW    WHERE   YYYYMMBILL=1 AND  BILLTYPE=11 AND  (BILLID NOT IN (SELECT BILLID FROM STOREMOVEM) )

	DELETE DetailBillFlow  WHERE   YYYYMMBILL=1  AND  BILLTYPE=10 AND  (BILLID NOT IN (SELECT BILLID FROM STOREQTCKM ) )
	DELETE DetailBillFlow  WHERE   YYYYMMBILL=1  AND  BILLTYPE=9 AND  (BILLID NOT IN (SELECT BILLID FROM STOREQTRKM ) )

	DELETE BANKBILLFLOW    WHERE   YYYYMMBILL=1 AND  BILLTYPE=3 AND  (BILLID NOT IN (SELECT BILLID FROM STOREQTSRM) )

	DELETE DetailBillFlow  WHERE   YYYYMMBILL=1  AND  BILLTYPE=2 AND  (BILLID NOT IN (SELECT BILLID FROM STOREXSCKM) )
	DELETE CLIENTBILLFLOW  WHERE   YYYYMMBILL=1 AND  BILLTYPE=2 AND  (BILLID NOT IN (SELECT BILLID FROM STOREXSCKM) )
	DELETE BANKBILLFLOW    WHERE   YYYYMMBILL=1 AND  BILLTYPE=2 AND  (BILLID NOT IN (SELECT BILLID FROM STOREXSCKM) )
	DELETE YunShuDWBILLFLOW    WHERE   YYYYMMBILL=1 AND  BILLTYPE=2 AND  (BILLID NOT IN (SELECT BILLID FROM STOREXSCKM) )

	DELETE CLIENTBILLFLOW  WHERE   YYYYMMBILL=1 AND  BILLTYPE=4 AND  (BILLID NOT IN (SELECT BILLID FROM STOREXSSKM) )
	DELETE BANKBILLFLOW    WHERE   YYYYMMBILL=1 AND  BILLTYPE=4 AND  (BILLID NOT IN (SELECT BILLID FROM STOREXSSKM) )

	DELETE DetailBillFlow  WHERE   YYYYMMBILL=1  AND  BILLTYPE=12 AND  (BILLID NOT IN (SELECT BILLID FROM STOREXSTHM) )
	DELETE CLIENTBILLFLOW  WHERE   YYYYMMBILL=1 AND  BILLTYPE=12 AND  (BILLID NOT IN (SELECT BILLID FROM STOREXSTHM) )
	DELETE BANKBILLFLOW    WHERE   YYYYMMBILL=1 AND  BILLTYPE=12 AND  (BILLID NOT IN (SELECT BILLID FROM STOREXSTHM) )

	DELETE DetailBillFlow  WHERE   YYYYMMBILL=1  AND  BILLTYPE=102  AND  (BILLID NOT IN (SELECT BILLID FROM STOREXSDDM) )		
	Update SetCol set ID='888' where ID='999'
END
----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG










--------------------------------------------------------------------
--Create by li fa zheng  2004/05/11             
--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[Update_GoodsTypeNew_fullname] (@LCode varchar(100))   --APSOFTENCRYPTION       WITH ENCRYPTION
AS

--declare local variables needed
declare @PLCode varchar(100)
declare @PPrevno varchar(100)

declare @DIndirect_no varchar(100)
declare @DDirect_no varchar(100)
declare @DSelf_no varchar(100)

declare @CLCode varchar(100)
declare @Name varchar(50)
declare @CPrevno varchar(100)
declare @CPrevPrevno varchar(100)
declare @LongName varchar(200)

declare @temp_no varchar(100)


--find the insert or update record in GoodsTypeNew

----update GoodsTypeNew set fullname= Name  where prevno='0000'
---以上指令时解决顶级的
----本过程是解决非顶级的fullname

select @PLCode=@LCode
    select @Name=Name, @CPrevno=Prevno from GoodsTypeNew where (LCode=@PLCode)
    set @LongName =@Name
--    set @LongName =''

  while exists(select * from GoodsTypeNew where LCode=@CPrevno and LCode<>Prevno )
  begin
    select @Name=Name, @CPrevno=Prevno from GoodsTypeNew where (LCode=@CPrevno)
--	print @Name
--	print @CPrevno
		set @LongName =@Name+'→'+@LongName
  end
---    select @Name=Name, @CPrevno=Prevno from GoodsTypeNew where (LCode=@CPrevno)
--	print @Name
--	print @CPrevno
--		set @LongName =@Name+'→'+@LongName

update   GoodsTypeNew set fullname= @LongName   where LCode=@LCode






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG















CREATE PROCEDURE [dbo].[Update_GoodsTypeNew_fullname_ALL] 
AS

declare @LCode varchar(100)
declare @SqlSTR varchar(2000)
declare @Step0 int
declare @Step1 int
declare @Step2 int
declare @Step3 int
declare @Step4 int
declare @Step5 int
declare @Step6 int
declare @Step7 int
declare @Step8 int
declare @Step9 int


    update GoodsTypeNew set fullname= Name where prevno='00'


    declare SM_Consign_GoodsTypeNew Cursor for Select  LCode    from GoodsTypeNew where prevno<>'00'

    Open SM_Consign_GoodsTypeNew

    fetch SM_Consign_GoodsTypeNew into @LCode 

    while @@fetch_status = 0            ----开始
    begin

	exec Update_GoodsTypeNew_fullname @LCode

    fetch SM_Consign_GoodsTypeNew into @LCode 

    END           ------- SM_Consign_GoodsTypeNew  WHILE

    close SM_Consign_GoodsTypeNew
    deallocate SM_Consign_GoodsTypeNew














----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG









--------------------------------------------------------------------
--Create by li fa zheng  2004/05/11             
--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[Update_Iteminfo_fullname] (@ItemBM varchar(100))   --APSOFTENCRYPTION       WITH ENCRYPTION
AS

--declare local variables needed
declare @PItemBM varchar(100)
declare @PPrevno varchar(100)

declare @DIndirect_no varchar(100)
declare @DDirect_no varchar(100)
declare @DSelf_no varchar(100)

declare @CItemBM varchar(100)
declare @ItemMC varchar(50)
declare @CPrevno varchar(100)
declare @CPrevPrevno varchar(100)
declare @LongName varchar(200)

declare @temp_no varchar(100)


--find the insert or update record in ItemInfo

----update iteminfo set fullname= itemmc  where prevno='0000'
---以上指令时解决顶级的
----本过程是解决非顶级的fullname

select @PItemBM=@ItemBM
    select @ItemMC=ItemMC, @CPrevno=Prevno from ItemInfo where (ItemBM=@PItemBM)
    set @LongName =@ItemMC
--    set @LongName =''

  while exists(select * from ItemInfo where ItemBM=@CPrevno and ItemBM<>Prevno )
  begin
    select @ItemMC=ItemMC, @CPrevno=Prevno from ItemInfo where (ItemBM=@CPrevno)
--	print @ItemMC
--	print @CPrevno
		set @LongName =@ItemMC+'→'+@LongName
  end
---    select @ItemMC=ItemMC, @CPrevno=Prevno from ItemInfo where (ItemBM=@CPrevno)
--	print @ItemMC
--	print @CPrevno
--		set @LongName =@ItemMC+'→'+@LongName

update   ItemInfo set fullname= @LongName   where ItemBM=@ItemBM





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG














CREATE PROCEDURE [dbo].[Update_Iteminfo_fullname_ALL] 
AS

declare @ItemBM varchar(100)
declare @SqlSTR varchar(2000)
declare @Step0 int
declare @Step1 int
declare @Step2 int
declare @Step3 int
declare @Step4 int
declare @Step5 int
declare @Step6 int
declare @Step7 int
declare @Step8 int
declare @Step9 int

---以下指令取得明细科目
---select * from iteminfo where itembm not in (select prevno from iteminfo) 
----
----Select *   from Iteminfo where (itembm = prevno) OR (itembm not in (select prevno from Iteminfo ))
-----取得明细科目 
---    update iteminfo set prevno='0000' where prevno IS NULL
---------

	select @Step0=Step0,@Step1=Step1,@Step2=Step2,@Step3=Step3,@Step4=Step4,@Step5=Step5,@Step6=Step6,@Step7=Step7,
		@Step8=Step8,@Step9=Step9  FROM  ACCINFO  WHERE GUID='0001'

-------------删除不规范科目

---	delete  Iteminfo  where len(ItemBM) NOT in (

	update  Iteminfo set prevno=substring(itembm,1, @Step0)       where len(itembm)=@Step0+@Step1
	update  Iteminfo set prevno=substring(itembm,1, @Step0+@Step1)       where len(itembm)=@Step0+@Step1+@Step2
	update  Iteminfo set prevno=substring(itembm,1, @Step0+@Step1+@Step2)       where len(itembm)=@Step0+@Step1+@Step2+@Step3
	update  Iteminfo set prevno=substring(itembm,1, @Step0+@Step1+@Step2+@Step3)       where len(itembm)=@Step0+@Step1+@Step2+@Step3+@Step4
	update  Iteminfo set prevno=substring(itembm,1, @Step0+@Step1+@Step2+@Step3+@Step4)       where len(itembm)=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5
	update  Iteminfo set prevno=substring(itembm,1, @Step0+@Step1+@Step2+@Step3+@Step4+@Step5)       where len(itembm)=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6
	update  Iteminfo set prevno=substring(itembm,1, @Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6)       where len(itembm)=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7
	update  Iteminfo set prevno=substring(itembm,1, @Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6++@Step7)       where len(itembm)=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7+@Step8
	update  Iteminfo set prevno=substring(itembm,1, @Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6++@Step7+@Step8)       where len(itembm)=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7+@Step8+@Step9


------先解决明细科目


    update iteminfo set Detailflag=1

    update iteminfo set prevno='0000' where len(itembm)<=4

    update iteminfo set Detailflag=0 where itembm in (select prevno from iteminfo) 

----------------------------
----现金流科目级数2-2-2-3-3  最多5级编码
	set @Step0=2
	set @Step1=2
	set @Step2=2
	set @Step3=3
	set @Step4=3

	update  CW_Cash set prevno=substring(CW_CashID,1, @Step0)       where len(CW_CashID)=@Step0+@Step1
	update  CW_Cash set prevno=substring(CW_CashID,1, @Step0+@Step1)       where len(CW_CashID)=@Step0+@Step1+@Step2
	update  CW_Cash set prevno=substring(CW_CashID,1, @Step0+@Step1+@Step2)       where len(CW_CashID)=@Step0+@Step1+@Step2+@Step3
	update  CW_Cash set prevno=substring(CW_CashID,1, @Step0+@Step1+@Step2+@Step3)       where len(CW_CashID)=@Step0+@Step1+@Step2+@Step3+@Step4

    update CW_Cash set Detailflag=1

    update CW_Cash set prevno='0000' where len(CW_CashID)<=2

    update CW_Cash set Detailflag=0 where CW_CashID in (select prevno from CW_Cash) 


----------------------以上解决明细科目问题

    update iteminfo set fullname= itemmc where prevno='0000'


    declare SM_Consign_Iteminfo Cursor for Select  ItemBM    from Iteminfo where prevno<>'0000'

    Open SM_Consign_Iteminfo

    fetch SM_Consign_Iteminfo into @ItemBM 

    while @@fetch_status = 0            ----开始
    begin

	exec Update_Iteminfo_fullname @ItemBM

    fetch SM_Consign_Iteminfo into @ItemBM 

    END           ------- SM_Consign_Iteminfo  WHILE

    close SM_Consign_Iteminfo
    deallocate SM_Consign_Iteminfo













----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG





--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE [dbo].[VENDORCGDDMXB]( @WHERESTING   varchar(1800)                       
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8)

declare @GOODSNAME  varchar(50)
declare @VENDORNAME  varchar(50)

declare @ID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @VENDORID  nvarchar(50)
declare @GOODSCODE  nvarchar(50)
declare @SpecName  nvarchar(50)
declare @ModelName  nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLCODE  nvarchar(50)
declare @BILLTYPE INT
declare @BILLDATE  datetime
declare @VENDORID00  nvarchar(50)
declare @PRICE NUMERIC(20, 6)
declare @TAXAMT NUMERIC(20, 2)
declare @WCunitQTY NUMERIC(20, 6)
declare @WCquantity NUMERIC(20, 6)
declare @zzunitQTY NUMERIC(20, 6)
declare @zzquantity NUMERIC(20, 6)
declare @WCTAXAMT NUMERIC(20, 6)
declare @TAXRATE  NUMERIC(20, 6)
declare @RATE  NUMERIC(20, 6)
declare @WEITAXAMT NUMERIC(20, 6)
declare @SUMWCTAXAMT NUMERIC(20, 6)
declare @SUMWEITAXAMT NUMERIC(20, 6)
declare @SUMTAXAMT NUMERIC(20, 6)
declare @UNITQTY NUMERIC(20, 6)
declare @quantity NUMERIC(20, 6)
declare @UNITPRICE NUMERIC(20, 6)
declare @DISC NUMERIC(20, 6)
declare    @PRICETYPE int

Create Table #temptable1
      (   VENDORID varchar(50)  NULL,
       GOODSID  varchar(10) ,
       GOODSCODE  varchar(30) ,
      BILLID  nvarchar(50)  NULL,
      BILLTYPE  INT ,
	[PRICE] NUMERIC(20, 6)  NULL ,
	[UNITQTY] NUMERIC(20, 6)  NULL ,
	[quantity] NUMERIC(20, 6)  NULL ,
	[DISC] NUMERIC(20, 6)  NULL ,
	[TAXRATE]NUMERIC(20, 6)  NULL ,
	   BILLDATE  datetime  NULL,
	[UNITPRICE] NUMERIC(20, 6)  NULL ,
	[WCunitQTY]NUMERIC(20, 6)  NULL ,
	[WCquantity]NUMERIC(20, 6)  NULL ,
	[zzunitQTY]NUMERIC(20, 6)  NULL ,
	[zzquantity]NUMERIC(20, 6)  NULL ,
	[TAXAMT]NUMERIC(20, 2)  NULL, 
	[PRICETYPE]    int  NULL, 
	       DETAILBILLFLOWID  varchar(10) 
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   VIEWCGDD.VENDORID,VIEWCGDD.GOODSID,GOODS.CODE AS GOODSCODE, BILLID,BILLTYPE,PRICE,UNITQTY,quantity,DISC,TAXRATE,BILLDATE '
           SELECT  @SQLSTR = @SQLSTR+' ,UNITPRICE,WCunitQTY,WCquantity,zzunitQTY,zzquantity,TAXAMT,PRICETYPE,DETAILBILLFLOWID  from VIEWCGDD   ,GOODS  '  + @WHERESTING +'  AND  VIEWCGDD.GOODSID = GOODS.GOODSID'
           SELECT  @SQLSTR = @SQLSTR+'  order by VIEWCGDD.VENDORID,VIEWCGDD.GOODSID,BILLDATE,DETAILBILLFLOWID '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
	   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   GOODSNAME  nvarchar(50)  NULL,
   GOODSCODE  nvarchar(50)  NULL,
   SpecName  nvarchar(50)  NULL,
   ModelName  nvarchar(50)  NULL,
   UNIT  nvarchar(10)  NULL,
	[UNITQTY] NUMERIC(20, 6)  NULL ,
	[quantity] NUMERIC(20, 6)  NULL ,
	[TAXAMT]NUMERIC(20, 2)  NULL, 
	[WCunitQTY] NUMERIC(20, 6)  NULL ,
	[WCquantity] NUMERIC(20, 6)  NULL ,
	[zzunitQTY] NUMERIC(20, 6)  NULL ,
	[zzquantity] NUMERIC(20, 6)  NULL ,
	[WCTAXAMT]NUMERIC(20, 6)  NULL ,
	[WEIunitQTY] NUMERIC(20, 6)  NULL ,
	[WEIquantity] NUMERIC(20, 6)  NULL ,
	[WEITAXAMT]NUMERIC(20, 6)  NULL 
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (select  VENDORID, GOODSID, BILLID,PRICE,UNITQTY,TAXRATE,BILLTYPE   from  #temptable1        )
                 begin
	    declare CGDDMXB_VENDOR Cursor for select  VENDORID, GOODSID, BILLID,PRICE,UNITQTY,quantity,TAXRATE,BILLTYPE ,DISC,UNITPRICE,WCunitQTY,WCquantity, zzunitQTY,zzquantity,TAXAMT,PRICETYPE  from  #temptable1  
---                                                            ORDER BY  VENDORID,  BILLDATE,DETAILBILLFLOWID,GOODSCODE
                                                            ORDER BY  VENDORID,  BILLDATE,BILLID,GOODSCODE
	    Open CGDDMXB_VENDOR

	    fetch CGDDMXB_VENDOR into   @VENDORID,@GOODSID,@BILLID,@PRICE,@UNITQTY,@quantity,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@WCunitQTY,@WCquantity,@zzunitQTY,@zzquantity,@TAXAMT,@PRICETYPE

                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @VENDORNAME =(SELECT NAME   FROM VENDOR  WHERE VENDORID=@VENDORID)
                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)

                 SELECT  @VENDORID00=@VENDORID

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                                           VALUES  (@COUNTID,@VENDORNAME)
		SELECT @SUMWCTAXAMT=0
		SELECT @SUMTAXAMT=0
		SELECT @SUMWEITAXAMT=0
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF  not( @VENDORID00 = @VENDORID)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,WCTAXAMT,TAXAMT,WEITAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMWCTAXAMT,@SUMTAXAMT,@SUMWEITAXAMT)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @VENDORNAME =(SELECT NAME   FROM VENDOR  WHERE VENDORID=@VENDORID)
		                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @VENDORID00=@VENDORID


			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                           	                VALUES  (@COUNTID,@VENDORNAME)
				SELECT @SUMWCTAXAMT=0
				SELECT @SUMTAXAMT=0
				SELECT @SUMWEITAXAMT=0
		END	
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

				--SELECT @RATE =RATE  FROM GOODSUNIT  WHERE GOODSID=@GOODSID AND UNITID=@UNITID

	  			SELECT @UNIT = (SELECT UNIT   FROM GOODS  WHERE GOODSID=@GOODSID)
				
			   SELECT @BILLCODE=(SELECT CODE   FROM STORECGDDM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STORECGDDM  WHERE BILLID=@BILLID)
               SELECT  @GOODSCODE=CODE,@GOODSNAME=Name,@SpecName=SpecName,@ModelName=ModelName     FROM GOODS  WHERE GOODSID=@GOODSID
	               if @PRICETYPE=1
		               begin  
		                 SET @WEITAXAMT=Round(ISNULL(@DISC,100)*0.01*(ISNULL(@quantity,0)-ISNULL(@WCquantity,0)-ISNULL(@zzquantity,0))*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
		                 SET @WCTAXAMT=Round(ISNULL(@DISC,100)*0.01*ISNULL(@WCquantity,0)*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
					   end
					   else
					   begin
		                 SET @WEITAXAMT=Round(ISNULL(@DISC,100)*0.01*(ISNULL(@unitqty,0)-ISNULL(@WCunitqty,0)-ISNULL(@zzunitqty,0))*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
		                 SET @WCTAXAMT=Round(ISNULL(@DISC,100)*0.01*ISNULL(@WCunitqty,0)*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
					   end
		                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,GOODSNAME,GOODSCODE,SpecName,ModelName,UNIT, UNITQTY,quantity,TAXAMT,WCunitQTY,WCquantity,zzunitQTY,zzquantity,WCTAXAMT,WEIunitQTY,WEIquantity,WEITAXAMT)
             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@GOODSNAME,@GOODSCODE,@SpecName,@ModelName,@UNIT,@UNITQTY,@quantity,
					                     @TAXAMT,
					                     ISNULL(@WCunitQTY,0) ,
					                     ISNULL(@WCquantity,0) ,
					                     ISNULL(@zzunitQTY,0) ,
					                     ISNULL(@zzquantity,0) ,					@WCTAXAMT,
					                      @UNITQTY-ISNULL(@WCunitQTY,0) -ISNULL(@zzunitQTY,0),
					                      @quantity-ISNULL(@WCquantity,0) -ISNULL(@zzquantity,0),@WEITAXAMT	)

				SELECT @SUMTAXAMT=@SUMTAXAMT+@TAXAMT
				SELECT @SUMWCTAXAMT=@SUMWCTAXAMT+@WCTAXAMT
				SELECT @SUMWEITAXAMT=@SUMWEITAXAMT+@WEITAXAMT
		
	    fetch CGDDMXB_VENDOR into   @VENDORID,@GOODSID,@BILLID,@PRICE,@UNITQTY,@quantity,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@WCunitQTY,@WCquantity,@zzunitQTY,@zzquantity,@TAXAMT,@PRICETYPE
 
	    END           ------- CGDDMXB_VENDOR  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,WCTAXAMT,TAXAMT,WEITAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMWCTAXAMT,@SUMTAXAMT,@SUMWEITAXAMT)

	    close CGDDMXB_VENDOR
	    deallocate CGDDMXB_VENDOR
        end     ------------  if exists

 SELECT *  FROM #temptable2         ORDER BY ID










----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE VENDORCGRKMXB( @WHERESTING   varchar(1800)
                      
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8)

declare @GOODSNAME  varchar(50)
declare @VENDORNAME  varchar(50)

declare @ID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @VENDORID  nvarchar(50)
declare @CaiZhi  varchar(50)
declare @ChanDi  varchar(50)
declare @FuzhuQTY  varchar(50)
declare @GOODSCODE  nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLCODE  nvarchar(50)
declare @BILLTYPE INT
declare @PRICETYPE INT
declare @BILLDATE00  datetime
declare @BILLDATE  datetime
declare @VENDORID00  nvarchar(50)
declare @PRICE NUMERIC(20,10)
declare @QUANTITY NUMERIC(20,10)
declare @TAXRATE  NUMERIC(20,10)
declare @SUMAMT NUMERIC(20,10)
declare @SUMTAXAMT NUMERIC(20,10)
declare @SUMDayAMT NUMERIC(20,10)
declare @SUMDayTAXAMT NUMERIC(20,10)
declare @AMT NUMERIC(20,10)
declare @TAXAMT NUMERIC(20,10)
declare @UNITQTY NUMERIC(20,10)
declare @UNITPRICE NUMERIC(20,10)
declare @DISC NUMERIC(20,10)
declare @VendorFlag smallint 
declare @VendorFlag00 smallint 
    

Create Table #temptable1
      (   VENDORID varchar(50)  NULL,
       GOODSID  varchar(10) ,
       GOODSCODE  varchar(30) ,
      BILLID  nvarchar(50)  NULL,
      BILLTYPE  INT ,
	[PRICE] NUMERIC(20,10)  NULL ,
	[QUANTITY] NUMERIC(20,10)  NULL ,
	[DISC] NUMERIC(20,10)  NULL ,
	[TAXRATE]NUMERIC(20,10)  NULL ,
	   BILLDATE  datetime  NULL,
	[UNITPRICE] NUMERIC(20,10)  NULL ,
	[UNITQTY]NUMERIC(20,10)  NULL ,
	       DETAILBILLFLOWID  varchar(10) ,
		     PRICETYPE  INT ,
	[AMT]NUMERIC(20,10)  NULL ,
	[TAXAMT]NUMERIC(20,10)  NULL, 
	[VendorFlag]smallint  NULL ,
       ChanDi  varchar(30) ,
       FuZhuQTY  varchar(30) ,
       CaiZhi  varchar(30) 
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   VIEWCGRK.VENDORID,VIEWCGRK.GOODSID,GOODS.CODE AS GOODSCODE, BILLID,BILLTYPE,PRICE,QUANTITY,DISC,TAXRATE,BILLDATE '
           SELECT  @SQLSTR = @SQLSTR+' ,UNITPRICE,UNITQTY,DETAILBILLFLOWID,PRICETYPE,amt,TAXAMT,VendorFlag,ChanDi,FuzhuQTY,CaiZhi   from VIEWCGRK   ,GOODS  '  + @WHERESTING +'  AND  VIEWCGRK.GOODSID = GOODS.GOODSID'
           SELECT  @SQLSTR = @SQLSTR+'  order by VIEWCGRK.VENDORID,VIEWCGRK.GOODSID,BILLDATE,DETAILBILLFLOWID '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
	   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   GOODSNAME  nvarchar(50)  NULL,
   GOODSCODE  nvarchar(50)  NULL,
   UNIT  nvarchar(10)  NULL,
	[QUANTITY] NUMERIC(20,10)  NULL ,
	[PRICE] NUMERIC(20,10)  NULL ,
	[TAXRATE]NUMERIC(20,10)  NULL ,
	[AMT]NUMERIC(20,10)  NULL ,
	[TAXAMT]NUMERIC(20,10)  NULL ,
	       PRICETYPENAME  varchar(10) ,
       ChanDi  varchar(30) ,
       FuzhuQTY varchar(30) ,
       CaiZhi  varchar(30) 
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (select  VENDORID, GOODSID, BILLID,PRICE,QUANTITY,TAXRATE,BILLTYPE   from  #temptable1        )
                 begin
	    declare CGRKMXB_VENDOR Cursor for select  VENDORID, GOODSID, BILLID,PRICE,QUANTITY,TAXRATE,BILLTYPE ,DISC,UNITPRICE,UNITQTY,PRICETYPE,amt,TAXAMT,VendorFlag,ChanDi,FuzhuQTY,CaiZhi,BILLDATE  from  #temptable1  
                                                            ORDER BY   VENDORID,VendorFlag, BILLDATE,GOODSCODE,DETAILBILLFLOWID
	    Open CGRKMXB_VENDOR

	    fetch CGRKMXB_VENDOR into   @VENDORID,@GOODSID,@BILLID,@PRICE,@QUANTITY,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@UNITQTY,@PRICETYPE,@amt,@TAXAMT,@VendorFlag,@ChanDi,@FuzhuQTY,@CaiZhi,@BILLDATE

                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @VENDORNAME =(SELECT NAME   FROM ViewVENDOR  WHERE VENDORID=@VENDORID  and VendorFlag=@VendorFlag)
                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)

                 SELECT  @VENDORID00=@VENDORID
                 SELECT  @VendorFlag00=@VendorFlag
                 SELECT  @BILLDATE00=@BILLDATE

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                                           VALUES  (@COUNTID,@VENDORNAME)
		SELECT @SUMAMT=0
		SELECT @SUMTAXAMT=0
		SELECT @SUMDayAMT=0
		SELECT @SUMDayTAXAMT=0

	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF  not( @BILLDATE00=@BILLDATE)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,AMT,TAXAMT)
                                           VALUES  (@COUNTID, '按日小计',@SUMDayAMT,@SUMDayTAXAMT)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

----		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
----			         SELECT  @VendorNAME =(SELECT NAME   FROM ViewVendor  WHERE VendorID=@VendorID  and VendorFlag=@VendorFlag)
----		                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @BILLDATE00=@BILLDATE


			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                           	                VALUES  (@COUNTID,@VendorNAME)
				SELECT @SUMDayAMT=0
				SELECT @SUMDayTAXAMT=0
		END	


		IF  not( @VENDORID00 = @VENDORID AND @VendorFlag00=@VendorFlag)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,AMT,TAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMAMT,@SUMTAXAMT)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @VENDORNAME =(SELECT NAME   FROM ViewVENDOR  WHERE VENDORID=@VENDORID  and VendorFlag=@VendorFlag)
		                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @VENDORID00=@VENDORID
		                 SELECT  @VendorFlag00=@VendorFlag

			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                           	                VALUES  (@COUNTID,@VENDORNAME)
				SELECT @SUMAMT=0
				SELECT @SUMTAXAMT=0
				SELECT @SUMDayAMT=0
				SELECT @SUMDayTAXAMT=0

		END	
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
				
			   IF @BILLTYPE=1
			  BEGIN
			   SELECT @BILLCODE=(SELECT CODE   FROM STORECGRKM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STORECGRKM  WHERE BILLID=@BILLID)
			  END
			   IF @BILLTYPE=7
			  BEGIN
			   SELECT @BILLCODE=(SELECT CODE   FROM STORECGTHM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STORECGTHM  WHERE BILLID=@BILLID)
			  END
		                 SELECT  @GOODSNAME=(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @GOODSCODE=(SELECT CODE   FROM GOODS  WHERE GOODSID=@GOODSID)

			   IF @PRICETYPE=1   --吨
			  BEGIN
		                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,GOODSNAME,GOODSCODE,UNIT, QUANTITY,PRICE,TAXRATE, AMT,TAXAMT,PRICETYPENAME,ChanDi,FuzhuQTY,CaiZhi)
             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@GOODSNAME,@GOODSCODE,@UNIT,@QUANTITY,@UNITPRICE,@TAXRATE,@AMT,@TAXAMT,'重量',@ChanDi,@FuzhuQTY,@CaiZhi)
			  END
			   IF @PRICETYPE=0    --
			  BEGIN
		                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,GOODSNAME,GOODSCODE,UNIT, QUANTITY,PRICE,TAXRATE, AMT,TAXAMT,PRICETYPENAME,ChanDi,FuzhuQTY,CaiZhi)
             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@GOODSNAME,@GOODSCODE,@UNIT,@UNITQTY,@UNITPRICE,@TAXRATE,@AMT,@TAXAMT,'数量',@ChanDi,@FuzhuQTY,@CaiZhi)
			  END

				SELECT @SUMAMT=@SUMAMT+@AMT
				SELECT @SUMTAXAMT=@SUMTAXAMT+@TAXAMT
				SELECT @SUMDayAMT=@SUMDayAMT+@AMT
				SELECT @SUMDayTAXAMT=@SUMDayTAXAMT+@TAXAMT
		
	    fetch CGRKMXB_VENDOR into   @VENDORID,@GOODSID,@BILLID,@PRICE,@QUANTITY,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@UNITQTY,@PRICETYPE,@amt,@TAXAMT,@VendorFlag,@ChanDi,@FuzhuQTY,@CaiZhi,@BILLDATE
 
	    END           ------- CGRKMXB_VENDOR  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,AMT,TAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMAMT,@SUMTAXAMT)

	    close CGRKMXB_VENDOR
	    deallocate CGRKMXB_VENDOR
        end     ------------  if exists

 SELECT *  FROM #temptable2         ORDER BY ID









----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG










--------------------------------------------------------------------
CREATE PROCEDURE VENDORGJRKMXB( 
				@BEGINDATE   varchar(10),
				@ENDDATE   varchar(10),
				@WHERESTING   varchar(1800)
                       
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8)

declare @GOODSNAME  varchar(50)
declare @VENDORNAME  varchar(50)

declare @ID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @VENDORID  nvarchar(50)
declare @GOODSCODE  nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLCODE  nvarchar(50)
declare @BILLTYPE INT
declare @BILLDATE  datetime
declare @VENDORID00  nvarchar(50)
declare @PRICE NUMERIC(20,10)
declare @QUANTITY NUMERIC(20,10)
declare @TAXRATE  NUMERIC(20,10)
declare @SUMAMT NUMERIC(20,10)
declare @AMT NUMERIC(20,10)
declare @UNITQTY NUMERIC(20,10)
declare @RETURNQTY NUMERIC(20,10)
declare @UNITPRICE NUMERIC(20,10)
declare @RATE NUMERIC(20,10)
declare @DISC NUMERIC(20,10)
    

Create Table #temptable1
      (   VENDORID varchar(50)  NULL,
       GOODSID  varchar(10) ,
       GOODSCODE  varchar(30) ,
      BILLID  nvarchar(50)  NULL,
      BILLTYPE  INT ,
	[PRICE] NUMERIC(20,10)  NULL ,
	[QUANTITY] NUMERIC(20,10)  NULL ,
	[DISC] NUMERIC(20,10)  NULL ,
	[TAXRATE]NUMERIC(20,10)  NULL ,
	   BILLDATE  datetime  NULL,
	[UNITPRICE] NUMERIC(20,10)  NULL ,
	[UNITQTY]NUMERIC(20,10)  NULL ,
	[RETURNQTY]NUMERIC(20,10)  NULL ,
	       DETAILBILLFLOWID  varchar(10) 
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   VIEWGJRK.VENDORID,VIEWGJRK.GOODSID,GOODS.CODE AS GOODSCODE, BILLID,BILLTYPE,PRICE,QUANTITY,DISC,TAXRATE,BILLDATE '
           SELECT  @SQLSTR = @SQLSTR+' ,UNITPRICE,UNITQTY,RETURNQTY,DETAILBILLFLOWID   from VIEWGJRK   ,GOODS  '  + @WHERESTING +'  AND  VIEWGJRK.GOODSID = GOODS.GOODSID'
           SELECT  @SQLSTR = @SQLSTR+'   AND   BILLDATE <= '+CHAR(39)+@ENDDATE +CHAR(39) +'  AND   BILLDATE >= '+CHAR(39)+@BEGINDATE+CHAR(39)
           SELECT  @SQLSTR = @SQLSTR+'  order by VIEWGJRK.VENDORID,VIEWGJRK.GOODSID,BILLDATE,DETAILBILLFLOWID '  
            EXEC( @SQLSTR)




Create Table #temptable10
      (   VENDORID varchar(50)  NULL,
	[QTY] NUMERIC(20,10)  NULL ,
	[AMT] NUMERIC(20,10)  NULL 
		)

-----------------------------------------这个地方应该为合计数

           SELECT  @SQLSTR = ' INSERT #temptable10  '
           SELECT  @SQLSTR = @SQLSTR+' select  VIEWGJRK.vendoriD,  SUM(ISNULL(QUANTITY,0))  AS QTY '
           SELECT  @SQLSTR = @SQLSTR+' , SUM(UNITPRICE*isnull(quantity,0))  AS AMT      from VIEWGJRK   ,GOODS    '  + @WHERESTING +'  AND  VIEWGJRK.GOODSID = GOODS.GOODSID'
           SELECT  @SQLSTR = @SQLSTR+ ' AND   BILLDATE < '+CHAR(39)+@BEGINDATE +CHAR(39)+'     AND   VIEWGJRK.GOODSID NOT IN (SELECT GOODSID FROM  #temptable1  )   '
---           SELECT  @SQLSTR = @SQLSTR+ ' AND   QUANTITY > 0   AND  ( QUANTITY-ISNULL(RETURNQTY,0)) > 0 '
           SELECT  @SQLSTR = @SQLSTR+'  GROUP  BY  VIEWGJRK.VENDORID   '  
           SELECT  @SQLSTR = @SQLSTR+'  order by  VIEWGJRK.VENDORID  '  
            EXEC( @SQLSTR)



Create Table #temptable2
      (ID  varchar(10) primary key,
	   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   GOODSNAME  nvarchar(50)  NULL,
   GOODSCODE  nvarchar(50)  NULL,
   UNIT  nvarchar(10)  NULL,
	[GRQTY] NUMERIC(20,10)  NULL ,
	[GRAMT] NUMERIC(20,10)  NULL ,
	[CHQTY]NUMERIC(20,10)  NULL ,
	[CHAMT]NUMERIC(20,10)  NULL ,
	[EAMT]NUMERIC(20,10)  NULL 
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (select  VENDORID, GOODSID, BILLID,PRICE,QUANTITY,TAXRATE,BILLTYPE   from  #temptable1        )
                 begin
	    declare GJRKMXB_VENDOR Cursor for select  VENDORID, GOODSID, BILLID,PRICE,QUANTITY,TAXRATE,BILLTYPE ,DISC,UNITPRICE,UNITQTY,RETURNQTY  from  #temptable1  
                                                            ORDER BY   VENDORID,GOODSCODE, BILLDATE,DETAILBILLFLOWID
	    Open GJRKMXB_VENDOR

	    fetch GJRKMXB_VENDOR into   @VENDORID,@GOODSID,@BILLID,@PRICE,@QUANTITY,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@UNITQTY,@RETURNQTY

                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @VENDORNAME =(SELECT NAME   FROM VENDOR  WHERE VENDORID=@VENDORID)
                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)

                 SELECT  @VENDORID00=@VENDORID

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                                           VALUES  (@COUNTID,@VENDORNAME)

		SELECT @SUMAMT=isnull(SUM(QUANTITY*unitPRICE),0)  FROM  VIEWGJRK  WHERE BILLDATE  < @BEGINDATE     AND VENDORID=@VENDORID

		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,EAMT)
                                           VALUES  (@COUNTID, ' 期    初',@SUMAMT)

	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF  not( @VENDORID00 = @VENDORID)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,EAMT)
                                           VALUES  (@COUNTID, '  期   末',@SUMAMT)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @VENDORNAME =(SELECT NAME   FROM VENDOR  WHERE VENDORID=@VENDORID)
		                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @VENDORID00=@VENDORID


			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                           	                VALUES  (@COUNTID,@VENDORNAME)
				SELECT @SUMAMT=isnull(SUM(QUANTITY*UNITPRICE),0)  FROM  VIEWGJRK  WHERE BILLDATE  < @BEGINDATE  AND VENDORID=@VENDORID
				          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
				          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

			                          INSERT    INTO   #temptable2  (ID, BILLCODE,EAMT)
                          		                 VALUES  (@COUNTID, ' 期    初',@SUMAMT)

		END	
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
	  			SELECT @UNIT = (SELECT UNIT   FROM GOODS  WHERE GOODSID=@GOODSID)
				
			   SELECT @BILLCODE=(SELECT CODE   FROM STOREGJRKM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STOREGJRKM  WHERE BILLID=@BILLID)
		                 SELECT  @GOODSNAME=(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @GOODSCODE=(SELECT CODE   FROM GOODS  WHERE GOODSID=@GOODSID)

				SELECT @SUMAMT=@SUMAMT+ROUND(@QUANTITY*@unitPRICE,2)
					IF @QUANTITY>0   
					BEGIN
			                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,GOODSNAME,GOODSCODE,UNIT, GRQTY,GRAMT,EAMT)
	             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@GOODSNAME,@GOODSCODE,@UNIT,@QUANTITY,
						ROUND(@QUANTITY*@UNITPRICE,2),@SUMAMT)
					END

					IF @QUANTITY<0   
					BEGIN
			                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,GOODSNAME,GOODSCODE,UNIT, CHQTY,CHAMT,EAMT)
	             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@GOODSNAME,@GOODSCODE,@UNIT,-@QUANTITY,
						-ROUND(@QUANTITY*@UNITPRICE,2),@SUMAMT)
					END


		
	    fetch GJRKMXB_VENDOR into   @VENDORID,@GOODSID,@BILLID,@PRICE,@QUANTITY,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@UNITQTY,@RETURNQTY
 
	    END           ------- GJRKMXB_VENDOR  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,EAMT)
                                           VALUES  (@COUNTID, '  期   末',@SUMAMT)

	    close GJRKMXB_VENDOR
	    deallocate GJRKMXB_VENDOR
        end     ------------  if exists

-----------------------------------------------------------------------------------------------------------------



	   if exists (select  VENDORID, AMT   from  #temptable10        )
                 begin
	    declare GJRKMXB_SEC_VENDOR Cursor for select  VENDORID,AMT from  #temptable10  
                                                            ORDER BY   VENDORID
	    Open GJRKMXB_SEC_VENDOR

	    fetch GJRKMXB_SEC_VENDOR into   @VENDORID,@sumAMT


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	                 SELECT  @VENDORNAME =(SELECT NAME   FROM VENDOR  WHERE VENDORID=@VENDORID)
	
             		    SELECT  @VENDORID00=@VENDORID

		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                                           VALUES  (@COUNTID,@VENDORNAME)

		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,EAMT)
                                           VALUES  (@COUNTID, '  期   初',@SUMAMT)
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,EAMT)
                                           VALUES  (@COUNTID, '  期   末',@SUMAMT)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)


		
	    fetch GJRKMXB_SEC_VENDOR into   @VENDORID,@sumAMT
 
	    END           ------- GJRKMXB_SEC_VENDOR  WHILE
	    close GJRKMXB_SEC_VENDOR
	    deallocate GJRKMXB_SEC_VENDOR
        end     ------------  if exists





 SELECT *  FROM #temptable2         ORDER BY ID




----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG










CREATE PROCEDURE VENDORGJRKYYYYMMDD(@Begin_Date   varchar(10) ,
                                                                                           @End_date   varchar(10) ,  
						           @LCODE  varchar(10),             ---如果LCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSCODE  varchar(20),             ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSNAME  varchar(20),             ---如果GOODSNAME  为‘GGGG’表示不对类别进行查询
                                                                                           @INF_COSTINGTYPEID   smallint      --------同价调拨标志   0  代表 不作为过滤条件
                       
                                                      )     --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @WHERESTING   varchar(1800)

                   set @now_date=(select   max(billDATE)   FROM  VIEWGJRK)
		
		IF @now_date IS NULL
		BEGIN
			SET @now_date='2030-12-12'
		END

--@WHERESTR='  and 1=1 '
		if     NOT (@LCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = '  AND   I.GOODSID IN ( select G.GOODSID from GoodsTypetree T, GOODS G where T.indirect_no = '+CHAR(39)+@LCODE+CHAR(39)+ '  AND T.self_no=G.LCODE )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  ='     '
 		END
		if     NOT (@GOODSCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  CODE LIKE   '+CHAR(39)+'%'+@GOODSCODE+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  =@WHERESTING+'     '
 		END
		if     NOT (@GOODSNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  NAME LIKE   '+CHAR(39)+'%'+@GOODSNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END
		if     NOT (@INF_COSTINGTYPEID=0)
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where INF_COSTINGTYPEID =  '+str(@INF_COSTINGTYPEID)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END

----------------------------------------------------
		SELECT @SQLSTR='	 select  I.VENDORID,       '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)   as BQTY, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)   as BAMOUNT, ' --期初金额
		SELECT @SQLSTR=@SQLSTR+'ISNULL(BE.INQTY,0)  AS INQTY   ,-ISNULL(BE00.INQTY,0)  AS OUTQTY,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(BE.INAMOUNT,0)  AS INAMOUNT  ,-ISNULL(BE00.INAMOUNT,0)  AS OUTAMOUNT,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0) '
		SELECT @SQLSTR=@SQLSTR+'+ isnull(BE.INQTY,0)+isnull(BE00.INQTY,0) as EQTY ,' --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)  '
                           SELECT @SQLSTR=@SQLSTR+'+ISNULL(BE.INAMOUNT,0)+ISNULL(BE00.INAMOUNT,0)       as EAMOUNT '--期初金额
		 SELECT @SQLSTR=@SQLSTR+' from VENDOR  AS  I  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select VENDORID,sum(QUANTITY) as BQTY ,SUM(round(QUANTITY*UNITPRICE,2))  AS BAMOUNT'
		 SELECT @SQLSTR=@SQLSTR+' from VIEWGJRK  '
		SELECT @SQLSTR=@SQLSTR+'  where    BILLDATE < '+char(39)+@begin_date+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by VENDORID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.VENDORID = I.VENDORID  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select VENDORID,sum(QUANTITY) as INQTY  ,sum(round(QUANTITY*UNITPRICE,2))  as INAMOUNT      '
		 SELECT @SQLSTR=@SQLSTR+' from VIEWGJRK  '
		SELECT @SQLSTR=@SQLSTR+' where  QUANTITY > 0  AND BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+@End_Date+char(39)
		SELECT @SQLSTR=@SQLSTR+' group by VENDORID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE on BE.VENDORID = I.VENDORID  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select VENDORID,sum(QUANTITY) as INQTY  ,sum(round(QUANTITY*UNITPRICE,2))  as INAMOUNT      '
		 SELECT @SQLSTR=@SQLSTR+' from VIEWGJRK  '
		SELECT @SQLSTR=@SQLSTR+' where   QUANTITY < 0  AND BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+@End_Date+char(39)
		SELECT @SQLSTR=@SQLSTR+' group by VENDORID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE00 on BE00.VENDORID = I.VENDORID  '
                          SELECT @SQLSTR=@SQLSTR+'  where     I. VENDORID in (select VENDORID from  VIEWGJRK   where    BILLDATE <='+char(39)+@End_Date+char(39)+')'  + @WHERESTING 
		SELECT @SQLSTR=@SQLSTR+'          order by  I.CODE                '   
------------------------------------------------------------------------
		EXEC(@SQLSTR)




----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE VENDORINOUTMXBREP(@VENDORID varchar(8) ,                        -----如果为0000则全部仓库
                                                                                            @Begin_Date   varchar(10) ,
                                                                                           @End_date   varchar(10) 
                        
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @end_dateAddone  datetime,
        @MAXBILLDATE  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8),
        @WHERESTING   varchar(1800)

declare @VENDORNAME  varchar(50)
declare @VENDORSTR  varchar(50)

declare @ID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare  @BILLTYPE  INTEGER
declare  @INOUTFLAG  INTEGER
declare @BILLCODE  nvarchar(50)
declare @BILLDATE  datetime
declare @BILLTYPENAME  nvarchar(50)
declare @INAMOUNT NUMERIC(20,10)
declare @OUTAMOUNT NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @EAMOUNTPREV NUMERIC(20,10)
---//==========
declare @BAMOUNT NUMERIC(20,10)
declare @MAXID  nvarchar(50)

                   set @now_date=(select   max(billDATE)   FROM VENDORbillflow )

                          IF @now_date IS NULL
		BEGIN
			set @now_date='2029-10-12'         ----以后纠正此特殊值，此值为调试程序用
		END
                       

                          SELECT    @WHERESTING  = '  AND     BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+ @End_date+char(39) 
                          SELECT    @VENDORSTR  = '  AND     VENDORID ='+char(39)+@VENDORID+char(39)


     

Create Table #temptable10
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL 
		)

Create Table #temptable1
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
    INOUTFLAG  INTEGER
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   ID , BILLID,BILLTYPE,BILLCODE,BILLDATE,BILLTYPE,  '
           SELECT  @SQLSTR = @SQLSTR+'INAMOUNT,OUTAMOUNT,EAMOUNT ,INOUTFLAG '
           SELECT  @SQLSTR = @SQLSTR+'  from VENDORbillflow   where yyyymmbill=1    '  + @WHERESTING+@VENDORSTR 
           SELECT  @SQLSTR = @SQLSTR+'  order by id '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
    INOUTFLAG  INTEGER
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (Select  ID,BILLID,BILLTYPE, BILLCODE,BILLDATE,BILLTYPENAME,
                                                     isnull(INAMOUNT,0) as INAMOUNT ,  isnull(OUTAMOUNT,0) as OUTAMOUNT ,
                                                     isnull(EAMOUNT,0) as EAMOUNT   from  #temptable1        )
                 begin
	    declare INOUTMXBREP Cursor for Select  ID,BILLID,BILLTYPE , BILLCODE,BILLDATE,BILLTYPENAME,
                                                       isnull(INAMOUNT,0) as INAMOUNT ,   isnull(OUTAMOUNT,0) as OUTAMOUNT ,
                                                     isnull(EAMOUNT,0) as EAMOUNT ,INOUTFLAG  from  #temptable1         ORDER BY BILLDATE,ID
	    Open INOUTMXBREP

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INAMOUNT,@OUTAMOUNT,@EAMOUNT,@INOUTFLAG

                 SELECT  @VENDORNAME=NAME   FROM VENDOR  WHERE VENDORID=@VENDORID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME         )
                                           VALUES  (@COUNTID, @VENDORNAME)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                           select @MAXBILLDATE=MAX(BILLDATE) FROM VENDORbillflow   WHERE  VENDORID=@VENDORID   AND     BILLDATE  < @begin_date    AND YYYYMMBILL=1
                           SELECT  @MAXID=MAX(ID)  FROM VENDORbillflow  WHERE  VENDORID=@VENDORID     AND  BILLDATE=@MAXBILLDATE   AND YYYYMMBILL=1
                                         IF @MAXID IS NULL
 			BEGIN
			SET  @BAMOUNT=0
			END
                                        ELSE
			BEGIN
	                           SELECT @BAMOUNT=EAMOUNT   FROM   VENDORbillflow  WHERE ID=@MAXID
			END
                                                              
                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID , '期初结存',@BAMOUNT)
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
                       SELECT  @BILLTYPENAME=NAME FROM  BILLNAME  WHERE @BILLTYPENAME=BILLTYPEID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF @INOUTFLAG=1 
		BEGIN
			SELECT @INAMOUNT=@INAMOUNT
			SELECT @OUTAMOUNT=0
		END
		IF @INOUTFLAG=-1 
		BEGIN
			SELECT @OUTAMOUNT=@INAMOUNT
			SELECT @INAMOUNT=0
		END

                          INSERT    INTO   #temptable2  (ID,BILLID,BILLTYPE, BILLCODE,BILLDATE,BILLTYPENAME,
                                                               INAMOUNT,OUTAMOUNT,EAMOUNT)
                                           VALUES  (@COUNTID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INAMOUNT,@OUTAMOUNT,@EAMOUNT)
 		    SET @EAMOUNTPREV=@EAMOUNT

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INAMOUNT,@OUTAMOUNT,@EAMOUNT,@INOUTFLAG
 

	    END           ------- INOUTMXBREP  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期末结存',@EAMOUNT)

	    close INOUTMXBREP
	    deallocate INOUTMXBREP
        end     ------------  if exists
---------------------------
---------解决当前仓库本期间未发生业务的货品
--                  delete    #temptable1
            ELSE
            BEGIN
                           select @MAXBILLDATE=MAX(BILLDATE) FROM VENDORbillflow   WHERE  VENDORID=@VENDORID   AND     BILLDATE  < @begin_date    AND YYYYMMBILL=1
                           SELECT  @MAXID=MAX(ID)  FROM VENDORbillflow  WHERE  VENDORID=@VENDORID     AND  BILLDATE=@MAXBILLDATE   AND YYYYMMBILL=1

	             	  SELECT    @ID=ID,@EAMOUNT=EAMOUNT    FROM  VENDORbillflow  WHERE    ID =  @MAXID

                 SELECT @VENDORNAME=NAME   FROM VENDOR  WHERE VENDORID=@VENDORID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME         )
                                           VALUES  (@COUNTID,@VENDORNAME)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                                                              
                          INSERT    INTO   #temptable2  (ID , BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期初结存',@EAMOUNT)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期末结存',@EAMOUNT)

---------------------------
	END




--------------------------

 SELECT *  FROM #temptable2         ORDER BY ID





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG

















CREATE PROCEDURE [dbo].[VENDORYYYYMMDD](  @Begin_Date   varchar(10) ,
                                                                                           @End_date   varchar(10) ,  
                                                                                           @YYYYMM  varchar(8),      --------为当前会计期间
						           @LCODE  varchar(10),             ---如果LCODE  为‘GGGG’表示不对类别进行查询
						           @VENDORCODE  varchar(20),             ---如果VENDORCODE  为‘GGGG’表示不对类别进行查询
						           @VENDORNAME  varchar(20),             ---如果VENDORNAME  为‘GGGG’表示不对类别进行查询
                                                           @ZEROFLAG   smallint      --------  0  代表 不作为过滤条件

                         
                                                      ) as

Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @WHERESTING   varchar(1800)
                   set @now_date=(select   max(billDATE)   FROM  VENDORBILLFLOW)
                          IF @now_date IS NULL
		BEGIN
			set @now_date='2009-12-12'         ----以后纠正此特殊值，此值为调试程序用
		END

		if     NOT (@LCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = '  AND   I.VENDORID IN ( select G.VENDORID from AREAtree T, VENDOR G where T.indirect_no = '+CHAR(39)+@LCODE+CHAR(39)+ '  AND T.self_no=G.AREAID )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  ='     '
 		END
		if     NOT (@VENDORCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.VENDORID IN ( select  VENDORID from VENDOR   where  CODE LIKE   '+CHAR(39)+'%'+@VENDORCODE+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  =@WHERESTING+'     '
 		END
		if     NOT (@VENDORNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.VENDORID IN ( select  VENDORID from VENDOR   where  NAME LIKE   '+CHAR(39)+'%'+@VENDORNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END

--                       print   @WHERESTING
----------------------------------------------------
		SELECT @SQLSTR='	 select  I.VENDORID,  I.CODE,  I.NAME,       '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0) -(isnull(BN.INAMOUNT,0)- isnull(BN00.INAMOUNT,0)) as BAMOUNT, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(BE.INAMOUNT,0)  AS INAMOUNT   ,ISNULL(BE00.INAMOUNT,0)  AS OUTAMOUNT,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0) -(isnull(BN.INAMOUNT,0)- isnull(BN00.INAMOUNT,0))'
		SELECT @SQLSTR=@SQLSTR+'+ isnull(BE.INAMOUNT,0)-isnull(BE00.INAMOUNT,0) as EAMOUNT' --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from VENDOR  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select VENDORID,sum(INAMOUNT*INOUTFLAG)  as INAMOUNT  '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from VENDORBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)
		SELECT @SQLSTR=@SQLSTR+'group by VENDORID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.VENDORID = I.VENDORID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select VENDORID,sum(BAMOUNT) as BAMOUNT '
		SELECT @SQLSTR=@SQLSTR+' from VENDORBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by VENDORID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.VENDORID = I.VENDORID  '
------------------------以上部分是取当前库存
		SELECT @SQLSTR=@SQLSTR+'  left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select VENDORID,sum(INAMOUNT) as INAMOUNT      '
		SELECT @SQLSTR=@SQLSTR+'  from VENDORBILLFLOW           '
		SELECT @SQLSTR=@SQLSTR+'  where YYYYMMBILL = 1    and BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+ @Now_Date+char(39) +'  AND INOUTFLAG =1'   
		SELECT @SQLSTR=@SQLSTR+' group by VENDORID'	
		SELECT @SQLSTR=@SQLSTR+' ) as BN on BN.VENDORID = I.VENDORID'  
		SELECT @SQLSTR=@SQLSTR+'  left outer join '
		SELECT @SQLSTR=@SQLSTR+'  (  '
		SELECT @SQLSTR=@SQLSTR+'select VENDORID,sum(INAMOUNT) as INAMOUNT     '
		SELECT @SQLSTR=@SQLSTR+' from VENDORBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+ @Now_Date +char(39) +' AND INOUTFLAG =-1 '  
		SELECT @SQLSTR=@SQLSTR+' group by VENDORID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BN00 on BN00.VENDORID = I.VENDORID  '
------------------------以上部分为取begin_date到Now_Date的库存
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select VENDORID,sum(INAMOUNT) as INAMOUNT   '
		SELECT @SQLSTR=@SQLSTR+' from VENDORBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+@End_Date+char(39)+' AND INOUTFLAG =1 '  
		SELECT @SQLSTR=@SQLSTR+' group by VENDORID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE on BE.VENDORID = I.VENDORID  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select VENDORID,sum(INAMOUNT) as INAMOUNT   '
		SELECT @SQLSTR=@SQLSTR+' from VENDORBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+@End_Date +char(39)+'AND INOUTFLAG =-1' 
		SELECT @SQLSTR=@SQLSTR+' group by VENDORID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE00 on BE00.VENDORID = I.VENDORID  '
                          SELECT @SQLSTR=@SQLSTR+'  where     I. VENDORID in (select VENDORID from VENDORBILLFLOW where YYYYMM >='+char(39)+@YYYYMM+char(39)+')'  + @WHERESTING 
	             SELECT @SQLSTR=@SQLSTR+'          order by  I.VENDORID                '    
------------------------------------------------------------------------
--		       print   @SQLSTR

Create Table #temptable2012YF
      (VENDORID  varchar(10) primary key,
	    CODE  varchar(100) ,
	    NAME  varchar(100) ,
	  BAMOUNT NUMERIC(20,10)  NULL, 
	  INAMOUNT NUMERIC(20,10)  NULL, 
	  OUTAMOUNT NUMERIC(20,10)  NULL, 
	   EAMOUNT NUMERIC(20,10)  NULL 
		)

		INSERT INTO  #temptable2012YF  EXEC(@SQLSTR)


		IF  @ZEROFLAG=0
		BEGIN
                     SELECT *  FROM  #temptable2012YF
		END
		IF  @ZEROFLAG=1
		BEGIN
                     SELECT *  FROM  #temptable2012YF  where EAMOUNT<>0
		END













----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












CREATE PROCEDURE [VENDOR_CACULATOR_YYYYMM ]  (
	@VENDORID  varchar(30),
	@YYYYMM  varchar(6)    )
AS 
 
declare @INOUTFLAG NUMERIC(20,10)
declare @INAMOUNT  NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @SUMBAMOUNT NUMERIC(20,10)            ---本期期初总金额
 
BEGIN

            select    @SUMBAMOUNT=isnull(BAMOUNT,0)   FROM   VENDORBILLFlow  where    (rtrim(VENDORID) = @VENDORID) 
						  and (rtrim(YYYYMM) = @YYYYMM) 	and   ( YYYYMMBILL=0   )  
                                       -------以上是期初数据
----------------------------------------------------------------
	    declare VENDOR_CACULATOR Cursor for Select  VENDORID , isnull(INAMOUNT,0) as INAMOUNT, INOUTFLAG, isnull(EAMOUNT,0) as EAMOUNT 
	                  from VENDORBILLFlow   where (rtrim(YYYYMM) >= @YYYYMM)  AND ( VENDORID=@VENDORID)   and   ( YYYYMMBILL=1   )  
             		      ORDER BY BILLDATE,ID

	    Open VENDOR_CACULATOR

	    fetch VENDOR_CACULATOR into @VENDORID,@INAMOUNT,@INOUTFLAG,@EAMOUNT


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
		 select    @SUMBAMOUNT=@SUMBAMOUNT+@INAMOUNT*@INOUTFLAG

	         	 UPDATE   VENDORBILLFLOW  set   EAMOUNT=@SUMBAMOUNT      WHERE CURRENT OF  VENDOR_CACULATOR

		    fetch VENDOR_CACULATOR into @VENDORID,@INAMOUNT,@INOUTFLAG,@EAMOUNT
 
	    END           ------- VENDOR_CACULATOR  WHILE

	    close VENDOR_CACULATOR
	    deallocate VENDOR_CACULATOR

-----------------------------------------------------------------------------------------------------------------------------------------------------------


END








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE YYYYMMPOSTBILL(  @YYYYMM varchar(8)   )   --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @end_dateAddone  datetime,
        @BILLDATE  datetime,
        @SQLSTR   varchar(8000)


declare @ID  nvarchar(50)
declare @NEWID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare  @BILLTYPE  INTEGER
declare @BILLCODE  nvarchar(50)
declare @SPECNAME  nvarchar(50)


Create Table #temptable888
      (ID  varchar(10)  NULL,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL
		)

Create Table #temptable999 
      (ID  varchar(10)  NULL,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL
		)

		           SELECT  @SQLSTR = ' INSERT #temptable888    '
		           SELECT  @SQLSTR = @SQLSTR+'  select  distinct   id,billid,billtype,billcode,billdate   from   DETAILBILLFLOW  '
		           SELECT  @SQLSTR = @SQLSTR+'  where billid is not null  and yyyymmbill=1 and  yyyymm =  '
		           SELECT  @SQLSTR = @SQLSTR+char(39)+@yyyymm+char(39)
		           SELECT  @SQLSTR = @SQLSTR+'   order by billdate ,id '
		            EXEC( @SQLSTR)

		           SELECT  @SQLSTR = ' INSERT #temptable999   '
		           SELECT  @SQLSTR = @SQLSTR+'  select  distinct   0001  AS  ID, billid,billtype,billcode,billdate    from   DETAILBILLFLOW  '
		           SELECT  @SQLSTR = @SQLSTR+'  where billid is not null  and yyyymmbill=1 and  yyyymm =  '
		           SELECT  @SQLSTR = @SQLSTR+char(39)+@yyyymm+char(39)
		           SELECT  @SQLSTR = @SQLSTR+'   order by billdate  '

		            EXEC( @SQLSTR)
			
	    declare SM_Consign_POSTBILL Cursor for  select    id,billid,billtype,billcode,billdate   from  #temptable999 

	    Open SM_Consign_POSTBILL

	    fetch SM_Consign_POSTBILL into @ID ,@billid,@billtype,@billcode,@billdate

	    while @@fetch_status = 0            ----开始
	    begin
			SELECT @NEWID =(SELECT  MAX(ID)  FROM #temptable888  WHERE BILLID=@billid   AND BILLTYPE=@billTYPE   )


		          UPDATE   #temptable999  set    ID=@NEWID
             			           WHERE CURRENT OF SM_Consign_POSTBILL

	    fetch SM_Consign_POSTBILL into @ID ,@billid,@billtype,@billcode,@billdate

	    END           ------- SM_Consign_POSTBILL  WHILE

	    close SM_Consign_POSTBILL
	    deallocate SM_Consign_POSTBILL

           
 SELECT  AA.id,AA.billid,AA.billtype,AA.billcode,AA.billdate,BB.VENDORID,BB.CLIENTID,BB.POSTMAN,BB.MAKEMAN ,BB.OLDBILLCODE,BB.MEMO,BB.EMPID,BB.BUMENID   FROM #temptable999   AS  AA ,VIEWBILL   AS BB
 WHERE  AA.BILLID= BB.BILLID AND   AA.BILLTYPE= BB.BILLTYPE        ORDER BY  aa.billdate, ID




----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE YunShuDWINOUTMXBREP(@YunShuDWID varchar(8) ,                        -----如果为0000则全部仓库
                                                                                            @Begin_Date   varchar(10) ,
                                                                                           @End_date   varchar(10) 
                        
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @end_dateAddone  datetime,
        @MAXBILLDATE  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8),
        @WHERESTING   varchar(1800)

declare @YunShuDWNAME  varchar(50)
declare @YunShuDWSTR  varchar(50)

declare @ID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare  @BILLTYPE  INTEGER
declare  @INOUTFLAG  INTEGER
declare @BILLCODE  nvarchar(50)
declare @BILLDATE  datetime
declare @BILLTYPENAME  nvarchar(50)
declare @INAMOUNT NUMERIC(20,10)
declare @OUTAMOUNT NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @EAMOUNTPREV NUMERIC(20,10)
---//==========
declare @BAMOUNT NUMERIC(20,10)
declare @MAXID  nvarchar(50)

                   set @now_date=(select   max(billDATE)   FROM YunShuDWbillflow )

                          IF @now_date IS NULL
		BEGIN
			set @now_date='2029-10-12'         ----以后纠正此特殊值，此值为调试程序用
		END
                       

                          SELECT    @WHERESTING  = '  AND     BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+ @End_date+char(39) 
                          SELECT    @YunShuDWSTR  = '  AND     YunShuDWID ='+char(39)+@YunShuDWID+char(39)


     

Create Table #temptable10
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL 
		)

Create Table #temptable1
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
    INOUTFLAG  INTEGER
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   ID , BILLID,BILLTYPE,BILLCODE,BILLDATE,BILLTYPE,  '
           SELECT  @SQLSTR = @SQLSTR+'INAMOUNT,OUTAMOUNT,EAMOUNT ,INOUTFLAG '
           SELECT  @SQLSTR = @SQLSTR+'  from YunShuDWbillflow   where yyyymmbill=1    '  + @WHERESTING+@YunShuDWSTR 
           SELECT  @SQLSTR = @SQLSTR+'  order by id '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
    INOUTFLAG  INTEGER
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (Select  ID,BILLID,BILLTYPE, BILLCODE,BILLDATE,BILLTYPENAME,
                                                     isnull(INAMOUNT,0) as INAMOUNT ,  isnull(OUTAMOUNT,0) as OUTAMOUNT ,
                                                     isnull(EAMOUNT,0) as EAMOUNT   from  #temptable1        )
                 begin
	    declare INOUTMXBREP Cursor for Select  ID,BILLID,BILLTYPE , BILLCODE,BILLDATE,BILLTYPENAME,
                                                       isnull(INAMOUNT,0) as INAMOUNT ,   isnull(OUTAMOUNT,0) as OUTAMOUNT ,
                                                     isnull(EAMOUNT,0) as EAMOUNT ,INOUTFLAG  from  #temptable1         ORDER BY BILLDATE,ID
	    Open INOUTMXBREP

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INAMOUNT,@OUTAMOUNT,@EAMOUNT,@INOUTFLAG

                 SELECT  @YunShuDWNAME=YunShuDWNAME   FROM YunShuDW  WHERE YunShuDWID=@YunShuDWID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME         )
                                           VALUES  (@COUNTID, @YunShuDWNAME)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                           select @MAXBILLDATE=MAX(BILLDATE) FROM YunShuDWbillflow   WHERE  YunShuDWID=@YunShuDWID   AND     BILLDATE  < @begin_date    AND YYYYMMBILL=1
                           SELECT  @MAXID=MAX(ID)  FROM YunShuDWbillflow  WHERE  YunShuDWID=@YunShuDWID     AND  BILLDATE=@MAXBILLDATE   AND YYYYMMBILL=1
                                         IF @MAXID IS NULL
 			BEGIN
			SET  @BAMOUNT=0
			END
                                        ELSE
			BEGIN
	                           SELECT @BAMOUNT=EAMOUNT   FROM   YunShuDWbillflow  WHERE ID=@MAXID
			END
                                                              
                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID , '期初结存',@BAMOUNT)
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
                       SELECT  @BILLTYPENAME=NAME FROM  BILLNAME  WHERE @BILLTYPENAME=BILLTYPEID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF @INOUTFLAG=1 
		BEGIN
			SELECT @INAMOUNT=@INAMOUNT
			SELECT @OUTAMOUNT=0
		END
		IF @INOUTFLAG=-1 
		BEGIN
			SELECT @OUTAMOUNT=@INAMOUNT
			SELECT @INAMOUNT=0
		END

                          INSERT    INTO   #temptable2  (ID,BILLID,BILLTYPE, BILLCODE,BILLDATE,BILLTYPENAME,
                                                               INAMOUNT,OUTAMOUNT,EAMOUNT)
                                           VALUES  (@COUNTID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INAMOUNT,@OUTAMOUNT,@EAMOUNT)
 		    SET @EAMOUNTPREV=@EAMOUNT

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INAMOUNT,@OUTAMOUNT,@EAMOUNT,@INOUTFLAG
 

	    END           ------- INOUTMXBREP  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期末结存',@EAMOUNT)

	    close INOUTMXBREP
	    deallocate INOUTMXBREP
        end     ------------  if exists
---------------------------
---------解决当前仓库本期间未发生业务的货品
--                  delete    #temptable1
            ELSE
            BEGIN
                           select @MAXBILLDATE=MAX(BILLDATE) FROM YunShuDWbillflow   WHERE  YunShuDWID=@YunShuDWID   AND     BILLDATE  < @begin_date    AND YYYYMMBILL=1
                           SELECT  @MAXID=MAX(ID)  FROM YunShuDWbillflow  WHERE  YunShuDWID=@YunShuDWID     AND  BILLDATE=@MAXBILLDATE   AND YYYYMMBILL=1

	             	  SELECT    @ID=ID,@EAMOUNT=EAMOUNT    FROM  YunShuDWbillflow  WHERE    ID =  @MAXID

                 SELECT @YunShuDWNAME=YunShuDWNAME   FROM YunShuDW  WHERE YunShuDWID=@YunShuDWID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME         )
                                           VALUES  (@COUNTID,@YunShuDWNAME)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                                                              
                          INSERT    INTO   #temptable2  (ID , BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期初结存',@EAMOUNT)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期末结存',@EAMOUNT)

---------------------------
	END




--------------------------

 SELECT *  FROM #temptable2         ORDER BY ID






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG


















CREATE PROCEDURE YunShuDWYYYYMMDD(  @Begin_Date   varchar(10) ,
                                                                                           @End_date   varchar(10) ,  
                                                                                           @YYYYMM  varchar(8),      --------为当前会计期间
						           @YunShuDWCODE  varchar(20),             ---如果YunShuDWCODE  为‘GGGG’表示不对类别进行查询
						           @YunShuDWNAME  varchar(20)             ---如果YunShuDWNAME  为‘GGGG’表示不对类别进行查询
                         
                                                      ) as

Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @WHERESTING   varchar(1800)
                   set @now_date=(select   max(billDATE)   FROM  YunShuDWBILLFLOW)
                          IF @now_date IS NULL
		BEGIN
			set @now_date='2009-12-12'         ----以后纠正此特殊值，此值为调试程序用
		END

			SELECT    @WHERESTING  ='     '
		if     NOT (@YunShuDWCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.YunShuDWID IN ( select  YunShuDWID from YunShuDW   where  CODE LIKE   '+CHAR(39)+'%'+@YunShuDWCODE+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  =@WHERESTING+'     '
 		END
		if     NOT (@YunShuDWNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.YunShuDWID IN ( select  YunShuDWID from YunShuDW   where  YunShuDWNAME LIKE   '+CHAR(39)+'%'+@YunShuDWNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END

---                       print   @WHERESTING
----------------------------------------------------
		SELECT @SQLSTR='	 select  I.YunShuDWID,  I.CODE,  I.YunShuDWNAME  as NAME,       '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0) -(isnull(BN.INAMOUNT,0)- isnull(BN00.INAMOUNT,0)) as BAMOUNT, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(BE.INAMOUNT,0)  AS INAMOUNT   ,ISNULL(BE00.INAMOUNT,0)  AS OUTAMOUNT,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0) -(isnull(BN.INAMOUNT,0)- isnull(BN00.INAMOUNT,0))'
		SELECT @SQLSTR=@SQLSTR+'+ isnull(BE.INAMOUNT,0)-isnull(BE00.INAMOUNT,0) as EAMOUNT' --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from YunShuDW  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select YunShuDWID,sum(INAMOUNT*INOUTFLAG)  as INAMOUNT  '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from YunShuDWBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)
		SELECT @SQLSTR=@SQLSTR+'group by YunShuDWID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.YunShuDWID = I.YunShuDWID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select YunShuDWID,sum(BAMOUNT) as BAMOUNT '
		SELECT @SQLSTR=@SQLSTR+' from YunShuDWBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by YunShuDWID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.YunShuDWID = I.YunShuDWID  '
------------------------以上部分是取当前库存
		SELECT @SQLSTR=@SQLSTR+'  left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select YunShuDWID,sum(INAMOUNT) as INAMOUNT      '
		SELECT @SQLSTR=@SQLSTR+'  from YunShuDWBILLFLOW           '
		SELECT @SQLSTR=@SQLSTR+'  where YYYYMMBILL = 1    and BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+ @Now_Date+char(39) +'  AND INOUTFLAG =1'   
		SELECT @SQLSTR=@SQLSTR+' group by YunShuDWID'	
		SELECT @SQLSTR=@SQLSTR+' ) as BN on BN.YunShuDWID = I.YunShuDWID'  
		SELECT @SQLSTR=@SQLSTR+'  left outer join '
		SELECT @SQLSTR=@SQLSTR+'  (  '
		SELECT @SQLSTR=@SQLSTR+'select YunShuDWID,sum(INAMOUNT) as INAMOUNT     '
		SELECT @SQLSTR=@SQLSTR+' from YunShuDWBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+ @Now_Date +char(39) +' AND INOUTFLAG =-1 '  
		SELECT @SQLSTR=@SQLSTR+' group by YunShuDWID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BN00 on BN00.YunShuDWID = I.YunShuDWID  '
------------------------以上部分为取begin_date到Now_Date的库存
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select YunShuDWID,sum(INAMOUNT) as INAMOUNT   '
		SELECT @SQLSTR=@SQLSTR+' from YunShuDWBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+@End_Date+char(39)+' AND INOUTFLAG =1 '  
		SELECT @SQLSTR=@SQLSTR+' group by YunShuDWID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE on BE.YunShuDWID = I.YunShuDWID  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select YunShuDWID,sum(INAMOUNT) as INAMOUNT   '
		SELECT @SQLSTR=@SQLSTR+' from YunShuDWBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+@End_Date +char(39)+'AND INOUTFLAG =-1' 
		SELECT @SQLSTR=@SQLSTR+' group by YunShuDWID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE00 on BE00.YunShuDWID = I.YunShuDWID  '
                          SELECT @SQLSTR=@SQLSTR+'  where     I. YunShuDWID in (select YunShuDWID from YunShuDWBILLFLOW where YYYYMM >='+char(39)+@YYYYMM+char(39)+')'  + @WHERESTING 
	             SELECT @SQLSTR=@SQLSTR+'          order by  I.YunShuDWID                '    
------------------------------------------------------------------------
---	       print   @SQLSTR

		EXEC(@SQLSTR)







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













CREATE PROCEDURE [YunShuDW_CACULATOR_YYYYMM ]  (
	@YunShuDWID  varchar(30),
	@YYYYMM  varchar(6)    )
AS 
 
declare @INOUTFLAG NUMERIC(20,10)
declare @INAMOUNT  NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @SUMBAMOUNT NUMERIC(20,10)            ---本期期初总金额
 
BEGIN

            select    @SUMBAMOUNT=isnull(BAMOUNT,0)   FROM   YunShuDWBILLFlow  where    (rtrim(YunShuDWID) = @YunShuDWID) 
						  and (rtrim(YYYYMM) = @YYYYMM) 	and   ( YYYYMMBILL=0   )  
                                       -------以上是期初数据
----------------------------------------------------------------
	    declare YunShuDW_CACULATOR Cursor for Select  YunShuDWID , isnull(INAMOUNT,0) as INAMOUNT, INOUTFLAG, isnull(EAMOUNT,0) as EAMOUNT 
	                  from YunShuDWBILLFlow   where (rtrim(YYYYMM) >= @YYYYMM)  AND ( YunShuDWID=@YunShuDWID)   and   ( YYYYMMBILL=1   )  
             		      ORDER BY BILLDATE,ID

	    Open YunShuDW_CACULATOR

	    fetch YunShuDW_CACULATOR into @YunShuDWID,@INAMOUNT,@INOUTFLAG,@EAMOUNT


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
		 select    @SUMBAMOUNT=@SUMBAMOUNT+@INAMOUNT*@INOUTFLAG

	         	 UPDATE   YunShuDWBILLFLOW  set   EAMOUNT=@SUMBAMOUNT      WHERE CURRENT OF  YunShuDW_CACULATOR

		    fetch YunShuDW_CACULATOR into @YunShuDWID,@INAMOUNT,@INOUTFLAG,@EAMOUNT
 
	    END           ------- YunShuDW_CACULATOR  WHILE

	    close YunShuDW_CACULATOR
	    deallocate YunShuDW_CACULATOR

-----------------------------------------------------------------------------------------------------------------------------------------------------------


END









----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












CREATE            PROCEDURE initialCW_initbala
AS


---  SET XACT_ABORT ON

/*  DELETE FROM InitRate WHERE MoneyID=99

   Delete InitRate 
   From InitRate i, Currency c
   Where   NOT EXISTS    (Select MoneyID 
                                              From Currency
                                              WHERE  C.MoneyID = I.MoneyID   ) 

  INSERT INTO INITRATE
  SELECT c.MoneyID,c.Rate
  FROM Currency c
  WHERE c.MoneyID<99
    AND NOT EXISTS (Select MoneyID 
                                 From InitRate
                                  Where MoneyID = c.MoneyID )


  DELETE From	InitRate
  WHERE MoneyID=99
  INSERT INTO InitRate (MoneyID,Rate)
  VALUES(99,1)

  DELETE CW_initbala
  FROM CW_initbala a,Subject b
  WHERE --MnyIDSUBID =MnyIDSUBID AND 20070417 by lyh 多余
         a.SUBID=b.SUBID 
        AND b.HSWBFlag<2
        AND a.MoneyID<>b.MoneyID 
        AND b.DetailFlag='T'
        AND a.MoneyID<>99
        AND (a.Debit=0 OR a.Debit IS NULL)
        AND (a.Credit=0 OR a.Credit IS null)
        AND (a.BALANCE=0 OR a.BALANCE IS null)
         AND (a.PLHAVEDONE=0 OR a.PLHAVEDONE IS null)

  DELETE CW_initbala
  FROM CW_initbala i
  WHERE i.MoneyID<>99 
       AND NOT EXISTS(select MoneyID  from InitRate where  i.MoneyID= MoneyID )
       OR NOT EXISTS (select SubID from subject  where  i.SubID = SubID )


  INSERT INTO CW_initbala(MONEYID,Rate,SUBID)
  SELECT A.MoneyID,A.RATE,B.SUBID
  FROM InitRate A, Subject b
  WHERE NOT EXISTS(SELECT * 
                   FROM CW_initbala c 
                   WHERE a.MoneyID=c.MoneyID 
                   AND b.SUBID=c.SUBID)
    AND (a.MoneyID=99
    OR b.HSWBFlag=2
    --OR b.DetailFlag='F'
    OR  (b.HSWBFlag<2 AND a.MONEYID=b.MoneyID))
    and b.DetailFlag='T'


  DELETE 
  FROM InitRate 
  WHERE MoneyID=99
*/

  insert into CW_INITBALA (itembm)
	select itembm from ItemInfo where detailflag=1 and (itembm NOT IN (select itembm from CW_INITBALA))	

  Delete CW_INITBALA where itembm not in ( select itembm from ItemInfo where detailflag=1 )

  UPDATE CW_initbala SET Debit=0 WHERE Debit IS Null
  UPDATE CW_initbala SET Credit=0 WHERE Credit IS Null
  UPDATE CW_initbala SET Balance=0 WHERE Balance IS Null
  UPDATE CW_initbala SET PLHAVEDONE=0 WHERE PLHAVEDONE IS Null
  UPDATE CW_initbala SET DCFlag=b.JHD From CW_initbala a, ItemInfo b  WHERE a.itembm=b.itembm










----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG







if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[APRICECACULATOR_STORE ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[APRICECACULATOR_STORE ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[APRICECACULATOR_STORE_XIAN ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[APRICECACULATOR_STORE_XIAN ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[APRICECACULATOR_YYYYMM ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[APRICECACULATOR_YYYYMM ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[APRICECACULATOR_YYYYMM_XIAN ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[APRICECACULATOR_YYYYMM_XIAN ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BANKINOUTMXBREP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BANKINOUTMXBREP]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BANKYYYYMMDD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BANKYYYYMMDD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BANK_CACULATOR_YYYYMM ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BANK_CACULATOR_YYYYMM ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[BETWEEN_CURR_YYYYMM]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[BETWEEN_CURR_YYYYMM]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Bs_Update_AREATree]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Bs_Update_AREATree]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Bs_Update_GoodsTypeTree]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Bs_Update_GoodsTypeTree]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Bs_Update_INTYPETree]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Bs_Update_INTYPETree]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Bs_Update_OUTTYPETree]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Bs_Update_OUTTYPETree]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CGRKGoodsPrice_Update]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CGRKGoodsPrice_Update]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CLIENTINOUTMXBREP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CLIENTINOUTMXBREP]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CLIENTXSCKMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CLIENTXSCKMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CLIENTXSDDMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CLIENTXSDDMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CLIENTYYYYMMDD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CLIENTYYYYMMDD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CLIENTYYYYMMDD_BJ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CLIENTYYYYMMDD_BJ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CLIENT_CACULATOR_YYYYMM ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CLIENT_CACULATOR_YYYYMM ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CREAT_QGD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CREAT_QGD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CREAT_STRING_BILLNAME]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CREAT_STRING_BILLNAME]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CREAT_STRING_BillSeeAbout]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CREAT_STRING_BillSeeAbout]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CREAT_STRING_FunctionM]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CREAT_STRING_FunctionM]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CREAT_STRING_SETCOL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CREAT_STRING_SETCOL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CREAT_STRING_Sys_DictTable]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CREAT_STRING_Sys_DictTable]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_BETWEEN_CURR_YYYYMM]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_BETWEEN_CURR_YYYYMM]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_BILL_XuHao_ChongPai]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_BILL_XuHao_ChongPai]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_BillFlow_insert_YYYYMM]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_BillFlow_insert_YYYYMM]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_CACULATOR_YYYYMM ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_CACULATOR_YYYYMM ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_DataToNext]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_DataToNext]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_DataToNextDel]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_DataToNextDel]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_Data_START]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_Data_START]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_Data_START_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_Data_START_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_DengZhang]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_DengZhang]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_DengZhang_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_DengZhang_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_GET_ItemInfo_ItemBM]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_GET_ItemInfo_ItemBM]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_GET_Next_Item_len]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_GET_Next_Item_len]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_GET_SUM]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_GET_SUM]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_GongShiZhiXing]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_GongShiZhiXing]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_INOUTMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_INOUTMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_JieZhuanSY]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_JieZhuanSY]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_KeMuYuEHZB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_KeMuYuEHZB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_LRBMB_CRAET_CW_LRB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_LRBMB_CRAET_CW_LRB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_LRB_JiSuan]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_LRB_JiSuan]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_RJZINOUTMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_RJZINOUTMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_ShiSuanPHB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_ShiSuanPHB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_UpdateCW_INITBALAtotal]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_UpdateCW_INITBALAtotal]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_XJLLBMB_CRAET_CW_XJLLB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_XJLLBMB_CRAET_CW_XJLLB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_XJLLB_JiSuan]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_XJLLB_JiSuan]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_XianJinLLFP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_XianJinLLFP]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_ZCFZBMB_CRAET_CW_ZCFZB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_ZCFZBMB_CRAET_CW_ZCFZB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_ZCFZB_JiSuan]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_ZCFZB_JiSuan]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[CW_ZongFenLeiZhang]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[CW_ZongFenLeiZhang]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Check_BILL_NO]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Check_BILL_NO]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Check_Cred_Code_NO]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Check_Cred_Code_NO]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DANJuXiaoShu_SET]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[DANJuXiaoShu_SET]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[DetailBillFlow_insert_YYYYMM]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[DetailBillFlow_insert_YYYYMM]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[FYKZBILLTREE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[FYKZBILLTREE]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETALLPRICE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETALLPRICE]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETCLIENTIDEAMOUNT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETCLIENTIDEAMOUNT]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETGOODSIDEQTY]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETGOODSIDEQTY]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETGOODSIDMEQTY]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETGOODSIDMEQTY]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETGOODSSQL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETGOODSSQL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETGoodsIDEQTYANDALL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETGoodsIDEQTYANDALL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETKEYCodeKEYVALUE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETKEYCodeKEYVALUE]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETKEYVALUE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETKEYVALUE]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETKEYVALUE00]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETKEYVALUE00]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETKEYVALUE4]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETKEYVALUE4]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETVENDORIDEAMOUNT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETVENDORIDEAMOUNT]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETXSPrice]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETXSPrice]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETXSPriceDays]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETXSPriceDays]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GET_APRICE ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GET_APRICE ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GET_BILL_NO]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GET_BILL_NO]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GET_CURR_YYYYMM_FlagPost]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GET_CURR_YYYYMM_FlagPost]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GET_CWPZ_BILLID]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GET_CWPZ_BILLID]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GET_CW_initbala_PingHeng]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GET_CW_initbala_PingHeng]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GET_Cred_Code_NO]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GET_Cred_Code_NO]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GET_EPRICE ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GET_EPRICE ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GET_GoodsTypeNew_PrevNO]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GET_GoodsTypeNew_PrevNO]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GET_ItemInfo_ItemBM]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GET_ItemInfo_ItemBM]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GET_MQTY_EQTY_2011]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GET_MQTY_EQTY_2011]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GETwb_py_FIRST]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GETwb_py_FIRST]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODSCGDDMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GOODSCGDDMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODSCGRKMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GOODSCGRKMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODSGJRKMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GOODSGJRKMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODSGJRKYYYYMMDD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GOODSGJRKYYYYMMDD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODSNAME_CF]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GOODSNAME_CF]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODSXSCKMLRMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GOODSXSCKMLRMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODSXSCKMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GOODSXSCKMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODSXSDDMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GOODSXSDDMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODS_STOREMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[GOODS_STOREMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Get_Max_Min_Date]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Get_Max_Min_Date]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[INSERTTOSecurity]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[INSERTTOSecurity]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[QTSRBILLTREE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[QTSRBILLTREE]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SM_DataToNext]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[SM_DataToNext]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SM_DataToNextDel]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[SM_DataToNextDel]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[SM_Data_START]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[SM_Data_START]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STOREINOUTMXBREP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STOREINOUTMXBREP]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORELEDGER]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORELEDGER]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORELEDGER_BJ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORELEDGER_BJ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORELEDGER_BJ_Creat_CGDD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORELEDGER_BJ_Creat_CGDD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORELEDGER_CRAET_PD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORELEDGER_CRAET_PD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORELEDGER_XIAN]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORELEDGER_XIAN]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STOREYYYYMMDD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STOREYYYYMMDD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CGDD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CGDD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CGDD_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CGDD_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CGFK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CGFK]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CGFK_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CGFK_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CGFP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CGFP]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CGFP_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CGFP_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CGRK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CGRK]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CGRK_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CGRK_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CGTH]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CGTH]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CGTH_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CGTH_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CKDB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CKDB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CKDB_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CKDB_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CKPD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CKPD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CKPD_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CKPD_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CSH]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CSH]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CSH_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CSH_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CW_PingZheng]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CW_PingZheng]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_CW_PingZheng_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_CW_PingZheng_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_Calculate_Aprice]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_Calculate_Aprice]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_FYKZ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_FYKZ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_FYKZ_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_FYKZ_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_GJRK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_GJRK]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_GJRK_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_GJRK_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_GJRK_DEL_CGRK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_GJRK_DEL_CGRK]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_INVOICE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_INVOICE]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_INVOICE_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_INVOICE_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_JGD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_JGD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_JGD_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_JGD_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_LIUH]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_LIUH]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_LIUH_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_LIUH_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_MOVE]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_MOVE]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_MOVE_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_MOVE_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_QGAD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_QGAD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_QGAD_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_QGAD_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_QGD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_QGD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_QGD_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_QGD_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_QTCK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_QTCK]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_QTCK_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_QTCK_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_QTRK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_QTRK]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_QTRK_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_QTRK_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_QTSR]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_QTSR]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_QTSR_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_QTSR_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_SUM_ALL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_SUM_ALL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_TALLY]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_TALLY]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_TALLY_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_TALLY_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_XSCK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_XSCK]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_XSCK_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_XSCK_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_XSDD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_XSDD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_XSDD_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_XSDD_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_XSFP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_XSFP]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_XSFP_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_XSFP_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_XSSK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_XSSK]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_XSSK_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_XSSK_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_XSTH]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_XSTH]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_XSTH_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_XSTH_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_YYYYMM_INSERT]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_YYYYMM_INSERT]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_YunFeiFK]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_YunFeiFK]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_YunFeiFK_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_YunFeiFK_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_ZCD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_ZCD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_ZCD_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_ZCD_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_ZFD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_ZFD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[STORE_ZFD_DEL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[STORE_ZFD_DEL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Store_Yue_JiSuan]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Store_Yue_JiSuan]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UPDATE_DATA]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[UPDATE_DATA]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Update_GoodsTypeNew_fullname]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Update_GoodsTypeNew_fullname]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Update_GoodsTypeNew_fullname_ALL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Update_GoodsTypeNew_fullname_ALL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Update_Iteminfo_fullname]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Update_Iteminfo_fullname]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[Update_Iteminfo_fullname_ALL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[Update_Iteminfo_fullname_ALL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VENDORCGDDMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[VENDORCGDDMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VENDORCGRKMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[VENDORCGRKMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VENDORGJRKMXB]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[VENDORGJRKMXB]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VENDORGJRKYYYYMMDD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[VENDORGJRKYYYYMMDD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VENDORINOUTMXBREP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[VENDORINOUTMXBREP]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VENDORYYYYMMDD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[VENDORYYYYMMDD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[VENDOR_CACULATOR_YYYYMM ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[VENDOR_CACULATOR_YYYYMM ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[YYYYMMPOSTBILL]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[YYYYMMPOSTBILL]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[YunShuDWINOUTMXBREP]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[YunShuDWINOUTMXBREP]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[YunShuDWYYYYMMDD]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[YunShuDWYYYYMMDD]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[YunShuDW_CACULATOR_YYYYMM ]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[YunShuDW_CACULATOR_YYYYMM ]
----------ENDFLAG

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[initialCW_initbala]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[initialCW_initbala]
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG










--------------------------------------------------------------------
--Create by li fa zheng  2004/07/01              
--    再版1：   2004-07-02        
----    功能：    分仓库核算单价
--
--
--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[APRICECACULATOR_STORE ]  (@GOODSID  varchar(30),@STOREID00  varchar(30),
@YYYYMM  varchar(6)    )  --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 
declare @INOUTFLAG NUMERIC(20,10)
declare @BQTY NUMERIC(20,10)
declare @BPRICE NUMERIC(20,10)
declare @INQTY NUMERIC(20,10)
declare @MINQTY NUMERIC(20,10)
declare @MEQTY NUMERIC(20,10)
declare @INQTYSUM NUMERIC(20,10)
declare @INAMOUNTSUM  NUMERIC(20,10)
declare @INPRICE NUMERIC(20,10)
declare @EQTY NUMERIC(20,10)
declare @EPRICE NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)

declare @NEWEQTY NUMERIC(20,10)
declare @MNEWEQTY NUMERIC(20,10)
declare @NEWEPRICE NUMERIC(20,10)
declare @NEWEAMOUNT NUMERIC(20,10)

declare @SUMBAMOUNT NUMERIC(20,10)            ---本期期初总金额
declare @SUMBQTY NUMERIC(20,10)                    ---本期期初总数量
declare @MSUMBQTY NUMERIC(20,10)                    ---本期期初总数量
declare @SUMBPRICE NUMERIC(20,10)                 ---本期期初加权价
declare @DBPRICE    NUMERIC(20,10)                 ---本期期初加权价

declare @ID varchar(22)           --单号

declare @INF_COSTINGTYPEID  INT                ---本期期初加权价

declare @ITEMNO varchar(15)               --明细存货编号
declare @BILLID varchar(22)           --单号

declare @BILLTYPE INT


 
BEGIN

	       ----解决总仓库存的问题   BEGIN
	            if not exists(select *  from GOODSINIT  where 
	                                                 (rtrim(GOODSID) = @GOODSID AND  (rtrim(STOREID) = @STOREID00) )
             		                                 and(rtrim(YYYYMM) = @YYYYMM)
             		                                 )       
	           BEGIN
		    insert into GOODSINIT 
		    (GOODSID,YYYYMM,STOREID,
		     BQTY,BPRICE,INQTY,OUTQTY,
		     EQTY,EPRICE,BAMOUNT,EAMOUNT	     )
		    Values
		    (@GOODSID,@YYYYMM,@STOREID00,
		     0,0,0,0,
		     0,0,0,0)    

	           END      ------IF   END
                     ----解决总仓库存的问题 END
------------------------------------------------------------------------------------
  	            select    @SUMBAMOUNT=isnull(BAMOUNT,0),@SUMBQTY=isnull(BQTY,0),@MSUMBQTY=isnull(MBQTY,0),
					@SUMBPRICE=isnull(BPRICE,0)   FROM  GOODSINIT  
             	                                    where    (rtrim(GOODSID) = @GOODSID)    and (rtrim(YYYYMM) = @YYYYMM)  AND  (rtrim(STOREID) = @STOREID00) 
                                       -------以上是期初数据

       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID

        IF    @INF_COSTINGTYPEID=3      ----------- IF    @INF_COSTINGTYPEID=3       BEGIN    全月平均一次计算价格
        BEGIN
                         select    @INQTYSUM =  SUM(INQTY),  @INAMOUNTSUM =  SUM(INQTY*INPRICE)   FROM DetailBillFlow
			where (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   AND  (rtrim(STOREID) = @STOREID00)   and   ( YYYYMMBILL=1   )  AND ( INOUTFLAG = 1)   AND BILLTYPE<>6   AND BILLTYPE<>12
                                          ------------以上是本期合计   不包括调拨单的部分
             		  if (@SUMBAMOUNT is null) 
		     set  @SUMBAMOUNT=0
		  if (@SUMBQTY is null)   
			set @SUMBQTY=0
		  if (@SUMBPRICE is null)   
			set @SUMBPRICE=0
		  if (@INAMOUNTSUM is null)   
			set @INAMOUNTSUM=0
		  if (@INQTYSUM is null)   
			set @INQTYSUM=0

                         SET      @INAMOUNTSUM = @SUMBAMOUNT+@INAMOUNTSUM
                         SET      @INQTYSUM = @SUMBQTY+@INQTYSUM
		  if (-0.0000001<@INQTYSUM and @INQTYSUM<0.0000001)
		  begin
		   set   @INQTYSUM=0
		  end 
		 IF  @INQTYSUM<>0
		  begin
                             SET      @SUMBPRICE=ROUND(@INAMOUNTSUM/ @INQTYSUM,6)
		  end 


	          UPDATE   DETAILBILLFLOW  set    INPRICE= @SUMBPRICE
                         where (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=1   )  AND  (rtrim(STOREID) = @STOREID00)  AND ( INOUTFLAG = -1  OR  BILLTYPE = 5   OR   BILLTYPE = 6  OR BILLTYPE = 12 )
        END     ----------- IF    @INF_COSTINGTYPEID=3       END    全月平均一次计算价格   特别处理盘点和调拨
----------------------------------------------------------------
        IF   ( @INF_COSTINGTYPEID=1) OR   ( @INF_COSTINGTYPEID=3)    ----------- IF    @INF_COSTINGTYPEID=1 和 ( @INF_COSTINGTYPEID=3)      BEGIN     移动加权方式
        BEGIN
	       ---------注意是分仓库核算成本价格，每个仓库数量都是不同的！
                    ---------移动加权、全月一次平均以及个别指定算法都是一样的（基本一样，不同之处以上部分就是）
	    declare APRICE_STORE Cursor READ_ONLY for Select ID, GOODSID ,
             		     isnull(INQTY,0) as INqty,isnull(INPRICE,0) as INPRICE ,
             		     isnull(EQTY,0) as EQTY , isnull(EPRICE,0) as EPRICE , INOUTFLAG,
		      isnull(EAMOUNT,0) as EAMOUNT ,BILLTYPE,ITEMNO,BILLID,
		       isnull(MINQTY,0) as MINqty,  isnull(MEQTY,0) as MEqty
---	                  from DetailBillFlow   where (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=1   )  AND  (rtrim(STOREID) = @STOREID00) 
	                  from DetailBillFlow   where (rtrim(YYYYMM) >= @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=1   )  AND  (rtrim(STOREID) = @STOREID00) 
             		      ORDER BY BILLDATE,ID

	    Open APRICE_STORE

	    fetch APRICE_STORE into @ID,@GOODSID,@INqty,@INPRICE,@Eqty,@EPRICE,@INOUTFLAG,@EAMOUNT, @BILLTYPE,@ITEMNO,@BILLID,@MINQTY,@MEQTY


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	         IF (@INOUTFLAG=1)   and (@BILLTYPE<>5)  and  (@BILLTYPE<>6)   and  (@BILLTYPE<>12) 
	         BEGIN
	          Select @NEWEqty=NEWQTY,@MNEWEqty=MNEWQTY,@NEWEPRICE=NEWPRICE,@NEWEAMOUNT=NEWAMOUNT
             		       from  APRICECACULATOR    (@SUMBQTY,@MSUMBQTY,@SUMBPRICE,@SUMBAMOUNT,@INqty,@MINqty,@INPRICE,@INOUTFLAG)
	             ---定义的函数APRICECACULATOR
	          UPDATE   DETAILBILLFLOW  set    EQTY=@NEWEQTY,MEQTY=@MNEWEQTY,EPRICE=@NEWEPRICE,EAMOUNT=@NEWEAMOUNT
             		          WHERE ID=@ID
	         END
	         IF ( @INOUTFLAG = -1   )         OR  (@INOUTFLAG = 1  AND @BILLTYPE = 6)     OR  (@INOUTFLAG = 1  AND @BILLTYPE = 12)  
	         BEGIN
	             ---定义的函数APRICECACULATOR
	                       if  (@INF_COSTINGTYPEID=1)
                                    BEGIN 
		          Select @NEWEqty=NEWQTY,@MNEWEqty=MNEWQTY,@NEWEPRICE=NEWPRICE,@NEWEAMOUNT=NEWAMOUNT
             			       from  APRICECACULATOR    (@SUMBQTY,@MSUMBQTY,@SUMBPRICE,@SUMBAMOUNT,@INqty,@MINqty,@SUMBPRICE,@INOUTFLAG)
		          UPDATE   DETAILBILLFLOW  set    EQTY=@NEWEQTY,MEQTY=@MNEWEQTY,EPRICE=@NEWEPRICE,EAMOUNT=@NEWEAMOUNT,INPRICE=@SUMBPRICE
             			          WHERE ID=@ID
                                    END
	                       if   @INF_COSTINGTYPEID=3
                                    BEGIN 
		          Select @NEWEqty=NEWQTY,@MNEWEqty=MNEWQTY,@NEWEPRICE=NEWPRICE,@NEWEAMOUNT=NEWAMOUNT
             			       from  APRICECACULATOR    (@SUMBQTY,@MSUMBQTY,@SUMBPRICE,@SUMBAMOUNT,@INqty,@MINqty,@INPRICE,@INOUTFLAG)
		          UPDATE   DETAILBILLFLOW  set    EQTY=@NEWEQTY, MEQTY=@MNEWEQTY,EPRICE=@NEWEPRICE,EAMOUNT=@NEWEAMOUNT
             			          WHERE ID=@ID
                                    END

	         END
	         IF    (@INOUTFLAG = 1)  AND (@BILLTYPE=5)    
	         BEGIN
	             ---定义的函数APRICECACULATOR
	                       if  (@INF_COSTINGTYPEID=1)  OR(  @INF_COSTINGTYPEID=3)
                                    BEGIN 
			SELECT @DBPRICE=(SELECT INPRICE FROM DetailBillFlow  WHERE YYYYMMBILL=1 AND BILLTYPE=5  AND BILLID=@BILLID  AND GOODSID=@GOODSID AND ITEMNO=@ITEMNO  AND INOUTFLAG=-1 )
		          Select @NEWEqty=NEWQTY,@MNEWEqty=MNEWQTY,@NEWEPRICE=NEWPRICE,@NEWEAMOUNT=NEWAMOUNT
             			       from  APRICECACULATOR    (@SUMBQTY,@MSUMBQTY,@SUMBPRICE,@SUMBAMOUNT,@INqty,@MINqty,@DBPRICE,@INOUTFLAG)
		          UPDATE   DETAILBILLFLOW  set    EQTY=@NEWEQTY, MEQTY=@MNEWEQTY,EPRICE=@NEWEPRICE,EAMOUNT=@NEWEAMOUNT,INPRICE=@DBPRICE
             			          WHERE ID=@ID
                                    END
	         END
	        set    @SUMBQTY=@NEWEqty
	        set    @MSUMBQTY=@MNEWEqty
	        set    @SUMBPRICE=@NEWEPRICE
	        set    @SUMBAMOUNT=@NEWEAMOUNT

	    fetch APRICE_STORE into @ID,@GOODSID,@INqty,@INPRICE,@Eqty,@EPRICE,@INOUTFLAG,@EAMOUNT, @BILLTYPE,@ITEMNO,@BILLID,@MINQTY,@MEQTY
 
	            update   GOODS   SET APRICE = @NEWEPRICE WHERE  GOODSID=@GOODSID

	    END           ------- APRICE_STORE  WHILE

	    close APRICE_STORE
	    deallocate APRICE_STORE

        END              -------------------        IF    @INF_COSTINGTYPEID=1    和 ( @INF_COSTINGTYPEID=3)     END
-----------------------------------------------------------------------------------------------------------------------------------------------------------


END




----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG








































--------------------------------------------------------------------
--Create by li fa zheng  2012/09/01              
--功能： 本会计期间核算先进先出成本
--
--
--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[APRICECACULATOR_STORE_XIAN ]  (@GOODSID  varchar(30),@STOREID00  varchar(30),
@YYYYMM  varchar(6)    )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 
declare @INOUTFLAG NUMERIC(20,6)
declare @BQTY NUMERIC(20,6)
declare @BPRICE NUMERIC(20,6)
declare @INQTY NUMERIC(20,6)
declare @INQTYSUM NUMERIC(20,6)
declare @INAMOUNTSUM  NUMERIC(20,6)
declare @INPRICE NUMERIC(20,6)
declare @EQTY NUMERIC(20,6)
declare @EPRICE NUMERIC(20,6)
declare @EAMOUNT NUMERIC(20,6)

declare @NEWEQTY NUMERIC(20,6)
declare @NEWEPRICE NUMERIC(20,6)
declare @NEWEAMOUNT NUMERIC(20,6)
declare @OUTAMOUNT NUMERIC(20,6)

declare @SUMBAMOUNT NUMERIC(20,6)            ---本期期初总金额
declare @SUMBQTY NUMERIC(20,6)                    ---本期期初总数量
declare @MSUMBQTY NUMERIC(20,6)                    ---本期期初总数量
declare @OUTQTY NUMERIC(20,6)                    ---本期期初总数量
declare @OUTMQTY NUMERIC(20,6)                    ---本期期初总数量
declare @KeYongQTY NUMERIC(20,6)                    ---本期期初总数量
declare @KeYongMQTY NUMERIC(20,6)                    ---本期期初总数量
declare @KeYongAMOUNT NUMERIC(20,6)                    ---本期期初总数量
declare @KeYongPrice NUMERIC(20,6)                    ---本期期初总数量
declare @TMPKeYongQTY NUMERIC(20,6)                    ---本期期初总数量
declare @TMPKeYongMQTY NUMERIC(20,6)                    ---本期期初总数量
declare @TMPKeYongAMOUNT NUMERIC(20,6)                    ---本期期初总数量
declare @TMPKeYongPrice NUMERIC(20,6)                    ---本期期初总数量
declare @TMPQTY NUMERIC(20,6)                    ---本期期初总数量
declare @TMPMQTY NUMERIC(20,6)                    ---本期期初总数量
declare @MINQTY NUMERIC(20,10)
declare @MEQTY NUMERIC(20,10)
declare @MNEWEqty NUMERIC(20,10)


declare @SUMBPRICE NUMERIC(20,6)                 ---本期期初加权价

declare @INF_COSTINGTYPEID  INT                ---本期期初加权价

declare @ITEMNO varchar(15)               --明细存货编号
declare @MINbilldate  datetime   
declare @Billdate  datetime   


declare @BILLID varchar(22)           --单号
declare @StoreID varchar(22)           --单号

declare @BILLTYPE INT

declare @ID varchar(50)           --单号
declare @KeYongID varchar(50)           --单号

 
BEGIN

------------------------------------------------------------------------------------
          SELECT   @SUMBAMOUNT=(SELECT    isnull(SUM(BAMOUNT),0)  FROM  DetailBillFlow     where    (rtrim(GOODSID) = @GOODSID)    and (rtrim(YYYYMM) = @YYYYMM)      AND  YYYYMMBILL=0   AND  (rtrim(STOREID) = @STOREID00) )
          SELECT   @SUMBQTY=(SELECT    isnull(SUM(BQTY),0)   FROM  DetailBillFlow     where    (rtrim(GOODSID) = @GOODSID)    and (rtrim(YYYYMM) = @YYYYMM)     AND  YYYYMMBILL=0  AND  (rtrim(STOREID) = @STOREID00) )
          SELECT   @MSUMBQTY=(SELECT    isnull(SUM(MBQTY),0)   FROM  DetailBillFlow     where    (rtrim(GOODSID) = @GOODSID)    and (rtrim(YYYYMM) = @YYYYMM)     AND  YYYYMMBILL=0  AND  (rtrim(STOREID) = @STOREID00) )


                          IF    @SUMBQTY<>0
                          BEGIN
		SELECT   @SUMBPRICE=@SUMBAMOUNT/@SUMBQTY
		END
                           ELSE
                          BEGIN
		SELECT   @SUMBPRICE=0
		END
                                       -------以上是期初数据

       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID

        IF   @INF_COSTINGTYPEID=6   ----------- IF    @INF_COSTINGTYPEID=1 和 ( @INF_COSTINGTYPEID=3)      BEGIN     移动加权方式
        BEGIN
	       ---------注意是分仓库核算成本价格，每个仓库数量都是不同的！
                    ---------移动加权、全月一次平均以及个别指定算法都是一样的（基本一样，不同之处以上部分就是）

		---算法设计，先核算出库单价

------------------恢复本会计期间的可用数量

/*		update DetailBillFlow set EQTY=StoreEqty,Eprice=STOREEPrice,EAMOUNT=StoreEAMOUNT
				 where (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2   )
						 AND INOUTFLAG = 1   
						 AND  (rtrim(STOREID) = @STOREID00) 

*/

		update DetailBillFlow set EQTY=INQTY,MEQTY=MINQTY,Eprice=INPRICE,EAMOUNT=INQTY*INPRICE
				 where (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2   )
						 AND INOUTFLAG = 1   
						 AND  (rtrim(STOREID) = @STOREID00) 
             		     


	    declare APRICE_TEMP Cursor READ_ONLY for Select ID, GOODSID ,StoreID,
             		     isnull(INQTY,0) as INqty,isnull(INPRICE,0) as INPRICE ,
             		     isnull(EQTY,0) as EQTY , isnull(EPRICE,0) as EPRICE , INOUTFLAG, isnull(EAMOUNT,0) as EAMOUNT ,
				BILLTYPE,BILLID,BILLDATE,
		       isnull(MINQTY,0) as MINqty,  isnull(MEQTY,0) as MEqty
	                  from DetailBillFlow   where (rtrim(YYYYMM) >= @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=1   )
						 AND  (rtrim(STOREID) = @STOREID00) 
             		      ORDER BY BILLDATE,ID

	    Open APRICE_TEMP

	    fetch APRICE_TEMP into @ID,@GOODSID,@StoreID,@INqty,@INPRICE,@Eqty,@EPRICE,@INOUTFLAG,@EAMOUNT, @BILLTYPE,@BILLID,@Billdate,@MINQTY,@MEQTY


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	         IF (@INOUTFLAG=1)   AND  (@BILLTYPE<>216)
	         BEGIN

			IF   @BILLTYPE=6
			BEGIN
				Select @INPRICE=@SUMBPRICE
			END
			 
		          Select @NEWEqty=NEWQTY,@MNEWEqty=MNEWQTY,@NEWEPRICE=NEWPRICE,@NEWEAMOUNT=NEWAMOUNT
	             	       from  APRICECACULATOR    (@SUMBQTY,@MSUMBQTY,@SUMBPRICE,@SUMBAMOUNT,@INqty,@MINqty,@INPRICE,@INOUTFLAG)
	             ---定义的函数APRICECACULATOR
	        	  UPDATE   DETAILBILLFLOW  set    EQTY=@NEWEQTY,MEQTY=@MNEWEQTY,EPRICE=@NEWEPRICE,EAMOUNT=@NEWEAMOUNT
             		          WHERE ID=@ID


			IF   @BILLTYPE=6
			BEGIN
		          UPDATE   DETAILBILLFLOW  set   INPRICE=@INPRICE
             		           WHERE ID=@ID

		          UPDATE   DETAILBILLFLOW  set   INPRICE=@INPRICE,EPRICE=@INPRICE,EAMOUNT=INQTY*@INPRICE
					where (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2   )
						 AND  (rtrim(STOREID) = @STOREID00)  AND BILLTYPE=6 AND BILLID=@BILLID
			END

--			print @NEWEQTY
	         END
	         IF ( @INOUTFLAG = -1   )  OR  (@INOUTFLAG = 1  AND @BILLTYPE=7)  
	         BEGIN

		         IF    (@BILLTYPE<>216)   
		         BEGIN

			----在这里先计算出库单价
			----	逐行提取
				set @OUTQTY=@INqty
				set @OUTMQTY=@MINqty
				set @KeYongQTY=0
				set @KeYongMQTY=0
				set @KeYongPrice=0
				set @KeYongAMOUNT=0

				if @BILLTYPE =7         -----处理采购退货单
				begin
				set @OUTQTY=-@INqty
				set @OUTMQTY=-@MINqty
				end
			

				while @OUTQTY>0
				begin
					

				print @OUTQTY

					select  @MINBILLDATE=MIN(BILLDATE) from DETAILBILLFLOW where Eqty > 0 and 
					  (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2 )
								 AND  (rtrim(STOREID) = @STOREID00)  

					select @KeYongID=min(ID) from DETAILBILLFLOW where Eqty > 0 and 
					  (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2 )
								 AND  (rtrim(STOREID) = @STOREID00)  AND  BILLDATE=@MinBILLDATE  
------假设存在的情况下
					select @TMPKeYongQTY=Eqty,@TMPKeYongMQTY=MEqty,@TMPKeyongPrice=Eprice,@TMPKeYongAMOUNT=EQTY*EPrice from DETAILBILLFLOW where ID=@KeYongID
					print @TMPKeYongQTY

					set @TMPQTY=@TMPKeYongQTY-@OUTQTY
					set @TMPMQTY=@TMPKeYongMQTY-@OUTMQTY
					if @TMPQTY<=0
					begin
					set @KeYongAMOUNT=@KeYongAMOUNT+@TMPKeYongAMOUNT
					update DETAILBILLFLOW set EQTY=0,MEQTY=0,EAMOUNT=0 where ID=@KeYongID
					set @OUTQTY=@OUTQTY-@TMPKeYongQTY
					set @OUTMQTY=@OUTMQTY-@TMPKeYongMQTY

					end
					else
					begin
					set @KeYongAMOUNT=@KeYongAMOUNT+@OUTQTY*@TMPKeyongPrice
					update DETAILBILLFLOW set EQTY=EQTY-@OUTQTY,MEQTY=MEQTY-@OUTMQTY where ID=@KeYongID
				print @KeYongID

					set @OUTQTY=@OUTQTY-@TMPKeYongQTY
					set @OUTMQTY=@OUTMQTY-@TMPKeYongMQTY
					end

				end     
			    
				if @INqty<>0 
				begin
					set @KeYongPrice=(@KeYongAMOUNT/@INqty)
				end

				if @BILLTYPE =7  and  @INqty<>0       -----处理采购退货单
				begin
				set @KeYongPrice=-(@KeYongAMOUNT/@INqty)
				end
			

				print @KeYongPrice
				
		          UPDATE   DETAILBILLFLOW  set    INPRICE=@KeYongPrice  WHERE ID=@ID

		          Select @NEWEqty=NEWQTY,@MNEWEqty=MNEWQTY,@NEWEPRICE=NEWPRICE,@NEWEAMOUNT=NEWAMOUNT
             			       from  APRICECACULATOR    (@SUMBQTY,@MSUMBQTY,@SUMBPRICE,@SUMBAMOUNT,@INqty,@MINqty,@KeYongPrice ,@INOUTFLAG)
		          UPDATE   DETAILBILLFLOW  set    EQTY=@NEWEQTY,MEQTY=@MNEWEQTY,EPRICE=@NEWEPRICE,EAMOUNT=@NEWEAMOUNT
             			          WHERE ID=@ID
		         END
	         END

-----------------------------------------------------
	         IF ( @INOUTFLAG = -1) AND (@BILLTYPE in (12,216)) 
	         BEGIN

--------------------------负数的处理

			----在这里先计算出库单价
			----	逐行提取
				set @OUTQTY=@INqty
				set @OUTMQTY=@MINqty
				set @KeYongQTY=0
				set @KeYongMQTY=0
				set @KeYongPrice=0
				set @KeYongAMOUNT=0

				set @OUTQTY=-@INqty
				set @OUTMQTY=-@MINqty
			

				while @OUTQTY>0
				begin
					

				print @OUTQTY
--------------------------------------销售退货、与退料单寻单价入库

					select  @MINBILLDATE=MIN(BILLDATE) from DETAILBILLFLOW where Eqty > 0 
						and INQTY>Eqty  AND
					  (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2 )
								 AND  (rtrim(STOREID) = @STOREID00)  

					select @KeYongID=MIN(ID) from DETAILBILLFLOW where Eqty > 0 
						and INQTY>Eqty AND
					  (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2 )
								 AND  (rtrim(STOREID) = @STOREID00)  AND  BILLDATE=@MinBILLDATE  
------假设存在的情况下
					select @TMPKeYongQTY=INQTY-Eqty,@TMPKeYongMQTY=MINQTY-MEqty,@TMPKeyongPrice=Eprice,@TMPKeYongAMOUNT=(INQTY-Eqty)*EPrice from DETAILBILLFLOW where ID=@KeYongID
					print @TMPKeYongQTY

					set @TMPQTY=@OUTQTY-@TMPKeYongQTY
					set @TMPMQTY=@OUTMQTY-@TMPKeYongMQTY
					if @TMPQTY>=0
					begin
					set @KeYongAMOUNT=@KeYongAMOUNT+@TMPKeYongQTY*@TMPKeyongPrice
					update DETAILBILLFLOW set EQTY=INQTY,MEQTY=MINQTY where ID=@KeYongID
					set @OUTQTY=@OUTQTY-@TMPKeYongQTY
					set @OUTMQTY=@OUTMQTY-@TMPKeYongMQTY
					end
					else
					begin
				print @KeYongID
					set @KeYongAMOUNT=@KeYongAMOUNT+@OUTQTY*@TMPKeyongPrice
					update DETAILBILLFLOW set EQTY=EQTY+@OUTQTY,MEQTY=MEQTY+@OUTMQTY where ID=@KeYongID
					set @OUTQTY=@OUTQTY-@TMPKeYongQTY
					set @OUTMQTY=@OUTMQTY-@TMPKeYongMQTY


					end

				end     
			    
----				set @KeYongPrice=(@KeYongAMOUNT/@INqty)

				set @KeYongPrice=-(@KeYongAMOUNT/@INqty)
			

				
		          UPDATE   DETAILBILLFLOW  set    INPRICE=@KeYongPrice  WHERE ID=@ID

		          Select @NEWEqty=NEWQTY,@MNEWEqty=MNEWQTY,@NEWEPRICE=NEWPRICE,@NEWEAMOUNT=NEWAMOUNT
             			       from  APRICECACULATOR    (@SUMBQTY,@MSUMBQTY,@SUMBPRICE,@SUMBAMOUNT,@INqty,@MINqty,@KeYongPrice ,@INOUTFLAG)
		          UPDATE   DETAILBILLFLOW  set    EQTY=@NEWEQTY,MEQTY=@MNEWEQTY,EPRICE=@NEWEPRICE,EAMOUNT=@NEWEAMOUNT
             			          WHERE ID=@ID

	         END
--------------------------------------------------------------------

	        set    @SUMBQTY=@NEWEqty
	        set    @MSUMBQTY=@MNEWEqty
	        set    @SUMBPRICE=@NEWEPRICE
	        set    @SUMBAMOUNT=@NEWEAMOUNT

	    fetch APRICE_TEMP into @ID,@GOODSID,@StoreID,@INqty,@INPRICE,@Eqty,@EPRICE,@INOUTFLAG,@EAMOUNT, @BILLTYPE,@BILLID,@Billdate,@MINQTY,@MEQTY
 
	            update   GOODS   SET APRICE = @NEWEPRICE WHERE  GOODSID=@GOODSID

	    END           ------- APRICE_TEMP  WHILE

	    close APRICE_TEMP
	    deallocate APRICE_TEMP

-----------------////
		update DetailBillFlow set EAMOUNT=EQTY*INPRICE
				 where (rtrim(YYYYMM) >= @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2   )
						 AND INOUTFLAG = 1   
						 AND  (rtrim(STOREID) = @STOREID00) 




        END              -------------------        IF    @INF_COSTINGTYPEID=1    和 ( @INF_COSTINGTYPEID=3)     END
-----------------------------------------------------------------------------------------------------------------------------------------------------------


END





















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG
















--------------------------------------------------------------------
--Create by li fa zheng  2004/07/01              
--    再版1：   2004-07-02        
--     功能： 本会计期间核算成本价
--
--
--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[APRICECACULATOR_YYYYMM ]  (@GOODSID  varchar(30),@STOREID00  varchar(30),
@YYYYMM  varchar(6)    )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 
declare @INOUTFLAG NUMERIC(20,10)
declare @BQTY NUMERIC(20,10)
declare @BPRICE NUMERIC(20,10)
declare @INQTY NUMERIC(20,10)
declare @MINQTY NUMERIC(20,10)
declare @INQTYSUM NUMERIC(20,10)
declare @INAMOUNTSUM  NUMERIC(20,10)
declare @INPRICE NUMERIC(20,10)
declare @EQTY NUMERIC(20,10)
declare @MEQTY NUMERIC(20,10)
declare @EPRICE NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)

declare @NEWEQTY NUMERIC(20,10)
declare @MNEWEQTY NUMERIC(20,10)
declare @NEWEPRICE NUMERIC(20,10)
declare @NEWEAMOUNT NUMERIC(20,10)

declare @SUMBAMOUNT NUMERIC(20,10)            ---本期期初总金额
declare @SUMBQTY NUMERIC(20,10)                    ---本期期初总数量
declare @MSUMBQTY NUMERIC(20,10)                    ---本期期初总数量
declare @SUMBPRICE NUMERIC(20,10)                 ---本期期初加权价

declare @INF_COSTINGTYPEID  INT                ---本期期初加权价

declare @ITEMNO varchar(15)               --明细存货编号


declare @BILLID varchar(22)           --单号
declare @ID varchar(22)           --单号

declare @BILLTYPE INT




 
BEGIN

	       ----解决总仓库存的问题   BEGIN
	            if not exists(select *  from GOODSINIT  where 
	                                                 (rtrim(GOODSID) = @GOODSID)
             		                                 and(rtrim(YYYYMM) = @YYYYMM AND  (rtrim(STOREID) = @STOREID00) )
             		                                 )       
	           BEGIN
		    insert into GOODSINIT 
		    (GOODSID,YYYYMM,STOREID,
		     BQTY,BPRICE,INQTY,OUTQTY,
		     EQTY,EPRICE,BAMOUNT,EAMOUNT	     )
		    Values
		    (@GOODSID,@YYYYMM,@STOREID00,
		     0,0,0,0,
		     0,0,0,0)    

	           END      ------IF   END
                     ----解决总仓库存的问题 END
------------------------------------------------------------------------------------
                          SELECT   @SUMBAMOUNT=(SELECT    isnull(SUM(BAMOUNT),0)  FROM  GOODSINIT    where    (rtrim(GOODSID) = @GOODSID)    and (rtrim(YYYYMM) = @YYYYMM)     )
                          SELECT   @SUMBQTY=(SELECT    isnull(SUM(BQTY),0)  FROM  GOODSINIT    where    (rtrim(GOODSID) = @GOODSID)    and (rtrim(YYYYMM) = @YYYYMM)     )
                          SELECT   @MSUMBQTY=(SELECT    isnull(SUM(MBQTY),0)  FROM  GOODSINIT    where    (rtrim(GOODSID) = @GOODSID)    and (rtrim(YYYYMM) = @YYYYMM)     )
                          IF    @SUMBQTY<>0
                          BEGIN
		SELECT   @SUMBPRICE=@SUMBAMOUNT/@SUMBQTY
		END
                           ELSE
                          BEGIN
		SELECT   @SUMBPRICE=0
		END
                                       -------以上是期初数据

       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID

        IF    @INF_COSTINGTYPEID=3      ----------- IF    @INF_COSTINGTYPEID=3       BEGIN    全月平均一次计算价格
        BEGIN
                         select    @INQTYSUM =  SUM(INQTY), @INAMOUNTSUM =  SUM(INQTY*INPRICE)   FROM DetailBillFlow
			where (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=1   )  AND( INOUTFLAG = 1)    AND BILLTYPE<>5   AND BILLTYPE<>6
                                          ------------以上是本期合计   不包括调拨单的部分
             		  if (@SUMBAMOUNT is null) 
		     set  @SUMBAMOUNT=0
		  if (@SUMBQTY is null)   
			set @SUMBQTY=0
		  if (@SUMBPRICE is null)   
			set @SUMBPRICE=0
		  if (@INAMOUNTSUM is null)   
			set @INAMOUNTSUM=0
		  if (@INQTYSUM is null)   
			set @INQTYSUM=0

                         SET      @INAMOUNTSUM = @SUMBAMOUNT+@INAMOUNTSUM
                         SET      @INQTYSUM = @SUMBQTY+@INQTYSUM
		  if (-0.0000001<@INQTYSUM and @INQTYSUM<0.0000001)
		  begin
		   set   @INQTYSUM=0
		  end 
                             SET      @SUMBPRICE=ROUND(@INAMOUNTSUM/  @INQTYSUM,10)

	          UPDATE   DETAILBILLFLOW  set    INPRICE= @SUMBPRICE
                         where (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=1   )  AND ( INOUTFLAG = -1  OR  BILLTYPE = 5   OR   BILLTYPE = 6  OR  BILLTYPE = 12)
        END     ----------- IF    @INF_COSTINGTYPEID=3       END    全月平均一次计算价格   特别处理盘点和调拨
----------------------------------------------------------------
        IF   ( @INF_COSTINGTYPEID=1) OR   ( @INF_COSTINGTYPEID=3)  OR ( @INF_COSTINGTYPEID=2)  ----------- IF    @INF_COSTINGTYPEID=1 和 ( @INF_COSTINGTYPEID=3)      BEGIN     移动加权方式
        BEGIN
	       ---------注意是分仓库核算成本价格，每个仓库数量都是不同的！
                    ---------移动加权、全月一次平均以及个别指定算法都是一样的（基本一样，不同之处以上部分就是）
	    declare APRICE_TEMP Cursor READ_ONLY for Select ID, GOODSID ,
             		     isnull(INQTY,0) as INqty,isnull(INPRICE,0) as INPRICE ,
             		     isnull(EQTY,0) as EQTY , isnull(EPRICE,0) as EPRICE , INOUTFLAG, isnull(EAMOUNT,0) as EAMOUNT ,BILLTYPE,
			 isnull(MINQTY,0) as MINqty,  isnull(MEQTY,0) as MEqty
	                  from DetailBillFlow   where (rtrim(YYYYMM) >= @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=1   )
             		      ORDER BY BILLDATE,ID

	    Open APRICE_TEMP

	    fetch APRICE_TEMP into @ID,@GOODSID,@INqty,@INPRICE,@Eqty,@EPRICE,@INOUTFLAG,@EAMOUNT, @BILLTYPE,@MINQTY,@MEQTY


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	         IF (@INOUTFLAG=1)   and (@BILLTYPE<>5)  and  (@BILLTYPE<>6)  AND  (@BILLTYPE<>12)
	         BEGIN
	          Select @NEWEqty=NEWQTY,@MNEWEqty=MNEWQTY,@NEWEPRICE=NEWPRICE,@NEWEAMOUNT=NEWAMOUNT
             		       from  APRICECACULATOR    (@SUMBQTY,@MSUMBQTY,@SUMBPRICE,@SUMBAMOUNT,@INqty,@MINqty,@INPRICE,@INOUTFLAG)
	             ---定义的函数APRICECACULATOR
	          UPDATE   DETAILBILLFLOW  set    EQTY=@NEWEQTY, MEQTY=@MNEWEQTY,EPRICE=@NEWEPRICE,EAMOUNT=@NEWEAMOUNT
             		           WHERE ID=@ID
	         END
	         IF ( @INOUTFLAG = -1   )              OR  (@INOUTFLAG = 1  AND @BILLTYPE=5)    OR  (@INOUTFLAG = 1  AND @BILLTYPE = 6)    OR  (@INOUTFLAG = 1  AND @BILLTYPE =12)  
	         BEGIN
	                       if  (@INF_COSTINGTYPEID=1)
                                    BEGIN 
			          Select @NEWEqty=NEWQTY,@MNEWEqty=MNEWQTY,@NEWEPRICE=NEWPRICE,@NEWEAMOUNT=NEWAMOUNT
			       from  APRICECACULATOR    (@SUMBQTY,@MSUMBQTY,@SUMBPRICE,@SUMBAMOUNT,@INqty,@MINqty,@SUMBPRICE,@INOUTFLAG)
	             ---定义的函数APRICECACULATOR
		          UPDATE   DETAILBILLFLOW  set    EQTY=@NEWEQTY,EPRICE=@NEWEPRICE,EAMOUNT=@NEWEAMOUNT,INPRICE=@SUMBPRICE
             			           WHERE ID=@ID
                                    END
	                       if  @INF_COSTINGTYPEID=3 
                                    BEGIN 
			          Select @NEWEqty=NEWQTY,@MNEWEqty=MNEWQTY,@NEWEPRICE=NEWPRICE,@NEWEAMOUNT=NEWAMOUNT
             			       from  APRICECACULATOR    (@SUMBQTY,@MSUMBQTY,@SUMBPRICE,@SUMBAMOUNT,@INqty,@MINqty,@INPRICE,@INOUTFLAG)
		          UPDATE   DETAILBILLFLOW  set    EQTY=@NEWEQTY,EPRICE=@NEWEPRICE,EAMOUNT=@NEWEAMOUNT
             			           WHERE ID=@ID
                                    END
	         END
		----------------begin
             		------此期间可以写反填出库单据的单价
                          ------以后在此写DETAILBILLFLOW中的INQTY和INPRICE相当于反填单据
                          -----只对出库单据操作，因为单据的成本价采用计算字段
		----------------end
	        set    @SUMBQTY=@NEWEqty
	        set    @MSUMBQTY=@MNEWEqty
	        set    @SUMBPRICE=@NEWEPRICE
	        set    @SUMBAMOUNT=@NEWEAMOUNT

	    fetch APRICE_TEMP into @ID,@GOODSID,@INqty,@INPRICE,@Eqty,@EPRICE,@INOUTFLAG,@EAMOUNT, @BILLTYPE,@MINQTY,@MEQTY
 
--	            update   GOODS   SET APRICE = @NEWEPRICE WHERE  GOODSID=@GOODSID

	    END           ------- APRICE_TEMP  WHILE

	    close APRICE_TEMP
	    deallocate APRICE_TEMP

        END              -------------------        IF    @INF_COSTINGTYPEID=1    和 ( @INF_COSTINGTYPEID=3)     END
-----------------------------------------------------------------------------------------------------------------------------------------------------------


END








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG







































--------------------------------------------------------------------
--Create by li fa zheng  2012/09/01              
--功能： 本会计期间核算先进先出成本
--
--
--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[APRICECACULATOR_YYYYMM_XIAN ]  (@GOODSID  varchar(30),@STOREID00  varchar(30),
@YYYYMM  varchar(6)    )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 
declare @INOUTFLAG NUMERIC(20,6)
declare @BQTY NUMERIC(20,6)
declare @BPRICE NUMERIC(20,6)
declare @INQTY NUMERIC(20,6)
declare @INQTYSUM NUMERIC(20,6)
declare @INAMOUNTSUM  NUMERIC(20,6)
declare @INPRICE NUMERIC(20,6)
declare @EQTY NUMERIC(20,6)
declare @EPRICE NUMERIC(20,6)
declare @EAMOUNT NUMERIC(20,6)

declare @NEWEQTY NUMERIC(20,6)
declare @NEWEPRICE NUMERIC(20,6)
declare @NEWEAMOUNT NUMERIC(20,6)
declare @OUTAMOUNT NUMERIC(20,6)

declare @SUMBAMOUNT NUMERIC(20,6)            ---本期期初总金额
declare @SUMBQTY NUMERIC(20,6)                    ---本期期初总数量
declare @MSUMBQTY NUMERIC(20,6)                    ---本期期初总数量
declare @OUTQTY NUMERIC(20,6)                    ---本期期初总数量
declare @OUTMQTY NUMERIC(20,6)                    ---本期期初总数量
declare @KeYongQTY NUMERIC(20,6)                    ---本期期初总数量
declare @KeYongMQTY NUMERIC(20,6)                    ---本期期初总数量
declare @KeYongAMOUNT NUMERIC(20,6)                    ---本期期初总数量
declare @KeYongPrice NUMERIC(20,6)                    ---本期期初总数量
declare @TMPKeYongQTY NUMERIC(20,6)                    ---本期期初总数量
declare @TMPKeYongMQTY NUMERIC(20,6)                    ---本期期初总数量
declare @TMPKeYongAMOUNT NUMERIC(20,6)                    ---本期期初总数量
declare @TMPKeYongPrice NUMERIC(20,6)                    ---本期期初总数量
declare @TMPQTY NUMERIC(20,6)                    ---本期期初总数量
declare @TMPMQTY NUMERIC(20,6)                    ---本期期初总数量
declare @MINQTY NUMERIC(20,10)
declare @MEQTY NUMERIC(20,10)
declare @MNEWEQTY NUMERIC(20,10)


declare @SUMBPRICE NUMERIC(20,6)                 ---本期期初加权价

declare @INF_COSTINGTYPEID  INT                ---本期期初加权价

declare @ITEMNO varchar(15)               --明细存货编号
declare @MINbilldate  datetime   
declare @Billdate  datetime   


declare @BILLID varchar(22)           --单号
declare @StoreID varchar(22)           --单号

declare @BILLTYPE INT

declare @ID varchar(50)           --单号
declare @KeYongID varchar(50)           --单号

 
BEGIN

------------------------------------------------------------------------------------
          SELECT   @SUMBAMOUNT=(SELECT    isnull(SUM(BAMOUNT),0)  FROM  DetailBillFlow     where    (rtrim(GOODSID) = @GOODSID)    and (rtrim(YYYYMM) = @YYYYMM)      AND  YYYYMMBILL=0    )
          SELECT   @SUMBQTY=(SELECT    isnull(SUM(BQTY),0)   FROM  DetailBillFlow     where    (rtrim(GOODSID) = @GOODSID)    and (rtrim(YYYYMM) = @YYYYMM)     AND  YYYYMMBILL=0   )
          SELECT   @MSUMBQTY=(SELECT    isnull(SUM(MBQTY),0)   FROM  DetailBillFlow     where    (rtrim(GOODSID) = @GOODSID)    and (rtrim(YYYYMM) = @YYYYMM)     AND  YYYYMMBILL=0   )


                          IF    @SUMBQTY<>0
                          BEGIN
		SELECT   @SUMBPRICE=@SUMBAMOUNT/@SUMBQTY
		END
                           ELSE
                          BEGIN
		SELECT   @SUMBPRICE=0
		END
                                       -------以上是期初数据

       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID

        IF   @INF_COSTINGTYPEID=6   ----------- IF    @INF_COSTINGTYPEID=1 和 ( @INF_COSTINGTYPEID=3)      BEGIN     移动加权方式
        BEGIN
	       ---------注意是分仓库核算成本价格，每个仓库数量都是不同的！
                    ---------移动加权、全月一次平均以及个别指定算法都是一样的（基本一样，不同之处以上部分就是）

		---算法设计，先核算出库单价

------------------恢复本会计期间的可用数量

/*		update DetailBillFlow set EQTY=StoreEqty,Eprice=STOREEPrice,EAMOUNT=StoreEAMOUNT
				 where (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2   )
						 AND INOUTFLAG = 1   
						 AND  (rtrim(STOREID) = @STOREID00) 

*/

		update DetailBillFlow set EQTY=INQTY,MEQTY=MINQTY,Eprice=INPRICE,EAMOUNT=INQTY*INPRICE
				 where (rtrim(YYYYMM) >= @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2   )
						 AND INOUTFLAG = 1   


	    declare APRICE_TEMP Cursor READ_ONLY for Select ID, GOODSID ,StoreID,
             		     isnull(INQTY,0) as INqty,isnull(INPRICE,0) as INPRICE ,
             		     isnull(EQTY,0) as EQTY , isnull(EPRICE,0) as EPRICE , INOUTFLAG, isnull(EAMOUNT,0) as EAMOUNT ,
				BILLTYPE,BILLID,BILLDATE,
			 isnull(MINQTY,0) as MINqty,  isnull(MEQTY,0) as MEqty

	                  from DetailBillFlow   where (rtrim(YYYYMM) >= @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=1   )
             		      ORDER BY BILLDATE,ID

	    Open APRICE_TEMP

	    fetch APRICE_TEMP into @ID,@GOODSID,@StoreID,@INqty,@INPRICE,@Eqty,@EPRICE,@INOUTFLAG,@EAMOUNT, @BILLTYPE,@BILLID,@Billdate,@MINQTY,@MEQTY


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	         IF (@INOUTFLAG=1)    AND  (@BILLTYPE<>216)
	         BEGIN

			IF   @BILLTYPE=6
			BEGIN
				Select @INPRICE=@SUMBPRICE
			END
			 
		          Select @NEWEqty=NEWQTY,@MNEWEqty=MNEWQTY,@NEWEPRICE=NEWPRICE,@NEWEAMOUNT=NEWAMOUNT
             		       from  APRICECACULATOR    (@SUMBQTY,@MSUMBQTY,@SUMBPRICE,@SUMBAMOUNT,@INqty,@MINqty,@INPRICE,@INOUTFLAG)
	             ---定义的函数APRICECACULATOR
		          UPDATE   DETAILBILLFLOW  set    EQTY=@NEWEQTY, MEQTY=@MNEWEQTY,EPRICE=@NEWEPRICE,EAMOUNT=@NEWEAMOUNT
             		           WHERE ID=@ID

			IF   @BILLTYPE=6
			BEGIN
		          UPDATE   DETAILBILLFLOW  set   INPRICE=@INPRICE
             		           WHERE ID=@ID

		          UPDATE   DETAILBILLFLOW  set   INPRICE=@INPRICE,EPRICE=@INPRICE,EAMOUNT=INQTY*@INPRICE
					where (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2   )
						  AND BILLTYPE=6 AND BILLID=@BILLID
			END

--			print @NEWEQTY
	         END
	         IF ( @INOUTFLAG = -1   )  OR  (@INOUTFLAG = 1  AND @BILLTYPE=7)  
	         BEGIN

		         IF    (@BILLTYPE<>216)   
		         BEGIN

			----在这里先计算出库单价
			----	逐行提取
				set @OUTQTY=@INqty
				set @OUTMQTY=@MINqty
				set @KeYongQTY=0
				set @KeYongMQTY=0
				set @KeYongPrice=0
				set @KeYongAMOUNT=0

				if @BILLTYPE =7         -----处理采购退货单
				begin
				set @OUTQTY=-@INqty
				set @OUTMQTY=-@MINqty
				end
			

				while @OUTQTY>0
				begin
					

				print @OUTQTY

					select  @MINBILLDATE=MIN(BILLDATE) from DETAILBILLFLOW where Eqty > 0 and 
					  (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2 )

					select @KeYongID=min(ID) from DETAILBILLFLOW where Eqty > 0 and 
					  (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2 )
								  AND  BILLDATE=@MinBILLDATE  
------假设存在的情况下
					select @TMPKeYongQTY=Eqty,@TMPKeYongMQTY=MEqty,@TMPKeyongPrice=Eprice,@TMPKeYongAMOUNT=EQTY*EPrice from DETAILBILLFLOW where ID=@KeYongID
					print @TMPKeYongQTY

					set @TMPQTY=@TMPKeYongQTY-@OUTQTY
					set @TMPMQTY=@TMPKeYongMQTY-@OUTMQTY
					if @TMPQTY<=0
					begin
					set @KeYongAMOUNT=@KeYongAMOUNT+@TMPKeYongAMOUNT
					update DETAILBILLFLOW set EQTY=0,MEQTY=0,EAMOUNT=0 where ID=@KeYongID
					set @OUTQTY=@OUTQTY-@TMPKeYongQTY
					set @OUTMQTY=@OUTMQTY-@TMPKeYongMQTY

					end
					else
					begin
					set @KeYongAMOUNT=@KeYongAMOUNT+@OUTQTY*@TMPKeyongPrice
					update DETAILBILLFLOW set EQTY=EQTY-@OUTQTY,MEQTY=MEQTY-@OUTMQTY where ID=@KeYongID
				print @KeYongID

					set @OUTQTY=@OUTQTY-@TMPKeYongQTY
					set @OUTMQTY=@OUTMQTY-@TMPKeYongMQTY
					end

				end     
			    
				set @KeYongPrice=(@KeYongAMOUNT/@INqty)

				if @BILLTYPE =7         -----处理采购退货单
				begin
				set @KeYongPrice=-(@KeYongAMOUNT/@INqty)
				end
			

				print @KeYongPrice
				
		          UPDATE   DETAILBILLFLOW  set    INPRICE=@KeYongPrice  WHERE ID=@ID

		          Select @NEWEqty=NEWQTY,@MNEWEqty=MNEWQTY,@NEWEPRICE=NEWPRICE,@NEWEAMOUNT=NEWAMOUNT
             			       from  APRICECACULATOR    (@SUMBQTY,@MSUMBQTY,@SUMBPRICE,@SUMBAMOUNT,@INqty,@MINqty,@KeYongPrice ,@INOUTFLAG)
		          UPDATE   DETAILBILLFLOW  set    EQTY=@NEWEQTY,MEQTY=@MNEWEQTY,EPRICE=@NEWEPRICE,EAMOUNT=@NEWEAMOUNT
             			          WHERE ID=@ID
		         END
	         END

-----------------------------------------------------
	         IF ( @INOUTFLAG = -1) AND (@BILLTYPE in (12,216)) 
	         BEGIN

--------------------------负数的处理

			----在这里先计算出库单价
			----	逐行提取
				set @OUTQTY=@INqty
				set @OUTMQTY=@MINqty
				set @KeYongQTY=0
				set @KeYongMQTY=0
				set @KeYongPrice=0
				set @KeYongAMOUNT=0

				set @OUTQTY=-@INqty
				set @OUTMQTY=-@MINqty
			

				while @OUTQTY>0
				begin
					

				print @OUTQTY
--------------------------------------销售退货、与退料单寻单价入库

					select  @MINBILLDATE=MIN(BILLDATE) from DETAILBILLFLOW where Eqty > 0 
						and INQTY>Eqty  AND
					  (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2 )

					select @KeYongID=MIN(ID) from DETAILBILLFLOW where Eqty > 0 
						and INQTY>Eqty AND
					  (rtrim(YYYYMM) = @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2 )
								 AND  BILLDATE=@MinBILLDATE  
------假设存在的情况下
					select @TMPKeYongQTY=INQTY-Eqty,@TMPKeYongMQTY=MINQTY-MEqty,@TMPKeyongPrice=Eprice,@TMPKeYongAMOUNT=(INQTY-Eqty)*EPrice from DETAILBILLFLOW where ID=@KeYongID
					print @TMPKeYongQTY

					set @TMPQTY=@OUTQTY-@TMPKeYongQTY
					set @TMPMQTY=@OUTMQTY-@TMPKeYongMQTY
					if @TMPQTY>=0
					begin
					set @KeYongAMOUNT=@KeYongAMOUNT+@TMPKeYongQTY*@TMPKeyongPrice
					update DETAILBILLFLOW set EQTY=INQTY,MEQTY=MINQTY where ID=@KeYongID
					set @OUTQTY=@OUTQTY-@TMPKeYongQTY
					set @OUTMQTY=@OUTMQTY-@TMPKeYongMQTY
					end
					else
					begin
				print @KeYongID
					set @KeYongAMOUNT=@KeYongAMOUNT+@OUTQTY*@TMPKeyongPrice
					update DETAILBILLFLOW set EQTY=EQTY+@OUTQTY,MEQTY=MEQTY+@OUTMQTY where ID=@KeYongID
					set @OUTQTY=@OUTQTY-@TMPKeYongQTY
					set @OUTMQTY=@OUTMQTY-@TMPKeYongMQTY


					end

				end     
			    
----				set @KeYongPrice=(@KeYongAMOUNT/@INqty)

				set @KeYongPrice=-(@KeYongAMOUNT/@INqty)
			

				
		          UPDATE   DETAILBILLFLOW  set    INPRICE=@KeYongPrice  WHERE ID=@ID

		          Select @NEWEqty=NEWQTY,@MNEWEqty=MNEWQTY,@NEWEPRICE=NEWPRICE,@NEWEAMOUNT=NEWAMOUNT
             			       from  APRICECACULATOR    (@SUMBQTY,@MSUMBQTY,@SUMBPRICE,@SUMBAMOUNT,@INqty,@MINqty,@KeYongPrice ,@INOUTFLAG)
		          UPDATE   DETAILBILLFLOW  set    EQTY=@NEWEQTY,MEQTY=@MNEWEQTY,EPRICE=@NEWEPRICE,EAMOUNT=@NEWEAMOUNT
             			          WHERE ID=@ID

	         END
--------------------------------------------------------------------

	        set    @SUMBQTY=@NEWEqty
	        set    @MSUMBQTY=@MNEWEqty
	        set    @SUMBPRICE=@NEWEPRICE
	        set    @SUMBAMOUNT=@NEWEAMOUNT

	    fetch APRICE_TEMP into @ID,@GOODSID,@StoreID,@INqty,@INPRICE,@Eqty,@EPRICE,@INOUTFLAG,@EAMOUNT, @BILLTYPE,@BILLID,@Billdate,@MINQTY,@MEQTY
 
	            update   GOODS   SET APRICE = @NEWEPRICE WHERE  GOODSID=@GOODSID

	    END           ------- APRICE_TEMP  WHILE

	    close APRICE_TEMP
	    deallocate APRICE_TEMP

-----------------////
		update DetailBillFlow set EAMOUNT=EQTY*INPRICE
				 where (rtrim(YYYYMM) >= @YYYYMM)  AND ( GOODSID=@GOODSID)   and   ( YYYYMMBILL=2   )
						 AND INOUTFLAG = 1   




        END              -------------------        IF    @INF_COSTINGTYPEID=1    和 ( @INF_COSTINGTYPEID=3)     END
-----------------------------------------------------------------------------------------------------------------------------------------------------------


END




















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG

















--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE BANKINOUTMXBREP(@BANKID varchar(8) ,                        -----如果为0000则全部仓库
                                                                                            @Begin_Date   varchar(10) ,
                                                                                           @End_date   varchar(10) 
                        
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @end_dateAddone  datetime,
        @MAXBILLDATE  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8),
        @WHERESTING   varchar(1800)

declare @BANKNAME  varchar(50)
declare @BANKSTR  varchar(50)

declare @ID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare  @BILLTYPE  INTEGER
declare  @INOUTFLAG  INTEGER
declare @BILLCODE  nvarchar(50)
declare @BILLDATE  datetime
declare @BILLTYPENAME  nvarchar(50)
declare @INAMOUNT NUMERIC(20,10)
declare @OUTAMOUNT NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @EAMOUNTPREV NUMERIC(20,10)
---//==========
declare @BAMOUNT NUMERIC(20,10)
declare @MAXID  nvarchar(50)

                   set @now_date=(select   max(billDATE)   FROM BANKbillflow)

                          IF @now_date IS NULL
		BEGIN
			set @now_date='2029-10-12'         ----以后纠正此特殊值，此值为调试程序用
		END
                       

                          SELECT    @WHERESTING  = '  AND     BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+ @End_date+char(39) 
                          SELECT    @BANKSTR  = '  AND     BANKID ='+char(39)+@BANKID+char(39)


     

Create Table #temptable10
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL 
		)

Create Table #temptable1
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
    INOUTFLAG  INTEGER
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   ID , BILLID,BILLTYPE,BILLCODE,BILLDATE,BILLTYPE,  '
           SELECT  @SQLSTR = @SQLSTR+'INAMOUNT,OUTAMOUNT,EAMOUNT ,INOUTFLAG '
           SELECT  @SQLSTR = @SQLSTR+'  from BANKbillflow   where yyyymmbill=1    '  + @WHERESTING+@BANKSTR 
           SELECT  @SQLSTR = @SQLSTR+'  order by id '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
    INOUTFLAG  INTEGER
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (Select  ID,BILLID,BILLTYPE, BILLCODE,BILLDATE,BILLTYPENAME,
                                                     isnull(INAMOUNT,0) as INAMOUNT ,  isnull(OUTAMOUNT,0) as OUTAMOUNT ,
                                                     isnull(EAMOUNT,0) as EAMOUNT   from  #temptable1        )
                 begin
	    declare INOUTMXBREP Cursor for Select  ID,BILLID,BILLTYPE , BILLCODE,BILLDATE,BILLTYPENAME,
                                                       isnull(INAMOUNT,0) as INAMOUNT ,   isnull(OUTAMOUNT,0) as OUTAMOUNT ,
                                                     isnull(EAMOUNT,0) as EAMOUNT ,INOUTFLAG  from  #temptable1         ORDER BY BILLDATE,ID
	    Open INOUTMXBREP

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INAMOUNT,@OUTAMOUNT,@EAMOUNT,@INOUTFLAG

                 SELECT  @BANKNAME= BANKNAME   FROM BANK  WHERE BANKID=@BANKID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME         )
                                           VALUES  (@COUNTID, @BANKNAME)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          select @MAXBILLDATE=MAX(BILLDATE) FROM BANKbillflow   WHERE  BANKID=@BANKID   AND     BILLDATE  < @begin_date    AND YYYYMMBILL=1
                           SELECT  @MAXID=MAX(ID)  FROM BANKbillflow  WHERE  BANKID=@BANKID     AND  BILLDATE=@MAXBILLDATE   AND YYYYMMBILL=1
                                         IF @MAXID IS NULL
 			BEGIN
			SET  @BAMOUNT=0
			END
                                        ELSE
			BEGIN
	                           SELECT @BAMOUNT=EAMOUNT   FROM   BANKbillflow  WHERE ID=@MAXID
			END
                                                              
                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID , '期初结存',@BAMOUNT)
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
                       SELECT  @BILLTYPENAME=NAME FROM  BILLNAME  WHERE @BILLTYPENAME=BILLTYPEID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF @INOUTFLAG=1 
		BEGIN
			SELECT @INAMOUNT=@INAMOUNT
			SELECT @OUTAMOUNT=0
		END
		IF @INOUTFLAG=-1 
		BEGIN
			SELECT @OUTAMOUNT=@INAMOUNT
			SELECT @INAMOUNT=0
		END

                          INSERT    INTO   #temptable2  (ID,BILLID,BILLTYPE, BILLCODE,BILLDATE,BILLTYPENAME,
                                                               INAMOUNT,OUTAMOUNT,EAMOUNT)
                                           VALUES  (@COUNTID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INAMOUNT,@OUTAMOUNT,@EAMOUNT)
 		    SET @EAMOUNTPREV=@EAMOUNT

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INAMOUNT,@OUTAMOUNT,@EAMOUNT,@INOUTFLAG
 

	    END           ------- INOUTMXBREP  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期末结存',@EAMOUNT)

	    close INOUTMXBREP
	    deallocate INOUTMXBREP
        end     ------------  if exists
---------------------------
---------解决当前仓库本期间未发生业务的货品
--                  delete    #temptable1
            ELSE
            BEGIN

                          select @MAXBILLDATE=MAX(BILLDATE) FROM BANKbillflow   WHERE  BANKID=@BANKID   AND     BILLDATE  < @begin_date    AND YYYYMMBILL=1
                           SELECT  @ID=MAX(ID)  FROM BANKbillflow  WHERE  BANKID=@BANKID     AND  BILLDATE=@MAXBILLDATE   AND YYYYMMBILL=1


	             	  SELECT    @ID=ID,@EAMOUNT=EAMOUNT    FROM  BANKbillflow  WHERE    ID = @ID   

                 SELECT @BANKNAME=BANKNAME   FROM BANK  WHERE BANKID=@BANKID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME         )
                                           VALUES  (@COUNTID,@BANKNAME)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                                                              
                          INSERT    INTO   #temptable2  (ID , BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期初结存',@EAMOUNT)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期末结存',@EAMOUNT)

---------------------------
	END




--------------------------

 SELECT *  FROM #temptable2         ORDER BY ID






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG
















CREATE PROCEDURE BANKYYYYMMDD(  @Begin_Date   varchar(10) ,
                                                                                           @End_date   varchar(10) ,  
                                                                                           @YYYYMM  varchar(8)    --------为当前会计期间
                         
                                                      ) as

Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000)
                   set @now_date=(select   max(billDATE)   FROM BANKBILLFLOW )
                          IF @now_date IS NULL
		BEGIN
			set @now_date='2009-12-12'         ----以后纠正此特殊值，此值为调试程序用
		END

----------------------------------------------------
		SELECT @SQLSTR='	 select  I.BANKID,   I.bankNAME,       '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0) -(isnull(BN.INAMOUNT,0)- isnull(BN00.INAMOUNT,0)) as BAMOUNT, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(BE.INAMOUNT,0)  AS INAMOUNT   ,ISNULL(BE00.INAMOUNT,0)  AS OUTAMOUNT,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0) -(isnull(BN.INAMOUNT,0)- isnull(BN00.INAMOUNT,0))'
		SELECT @SQLSTR=@SQLSTR+'+ isnull(BE.INAMOUNT,0)-isnull(BE00.INAMOUNT,0) as EAMOUNT' --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from BANK  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select BANKID,sum(INAMOUNT*INOUTFLAG)  as INAMOUNT  '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from BANKBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)
		SELECT @SQLSTR=@SQLSTR+'group by BANKID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.BANKID = I.BANKID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select BANKID,sum(BAMOUNT) as BAMOUNT '
		SELECT @SQLSTR=@SQLSTR+' from BANKBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by BANKID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.BANKID = I.BANKID  '
------------------------以上部分是取当前库存
		SELECT @SQLSTR=@SQLSTR+'  left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select BANKID,sum(INAMOUNT) as INAMOUNT      '
		SELECT @SQLSTR=@SQLSTR+'  from BANKBILLFLOW           '
		SELECT @SQLSTR=@SQLSTR+'  where YYYYMMBILL = 1    and BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+ @Now_Date+char(39) +'  AND INOUTFLAG =1'   
		SELECT @SQLSTR=@SQLSTR+' group by BANKID'	
		SELECT @SQLSTR=@SQLSTR+' ) as BN on BN.BANKID = I.BANKID'  
		SELECT @SQLSTR=@SQLSTR+'  left outer join '
		SELECT @SQLSTR=@SQLSTR+'  (  '
		SELECT @SQLSTR=@SQLSTR+'select BANKID,sum(INAMOUNT) as INAMOUNT     '
		SELECT @SQLSTR=@SQLSTR+' from BANKBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+ @Now_Date +char(39) +' AND INOUTFLAG =-1 '  
		SELECT @SQLSTR=@SQLSTR+' group by BANKID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BN00 on BN00.BANKID = I.BANKID  '
------------------------以上部分为取begin_date到Now_Date的库存
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select BANKID,sum(INAMOUNT) as INAMOUNT   '
		SELECT @SQLSTR=@SQLSTR+' from BANKBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+@End_Date+char(39)+' AND INOUTFLAG =1 '  
		SELECT @SQLSTR=@SQLSTR+' group by BANKID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE on BE.BANKID = I.BANKID  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select BANKID,sum(INAMOUNT) as INAMOUNT   '
		SELECT @SQLSTR=@SQLSTR+' from BANKBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+@End_Date +char(39)+'AND INOUTFLAG =-1' 
		SELECT @SQLSTR=@SQLSTR+' group by BANKID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE00 on BE00.BANKID = I.BANKID  '
                          SELECT @SQLSTR=@SQLSTR+'   where     I. BANKID in (select BANKID from BANKBILLFLOW where YYYYMM>='+char(39)+@YYYYMM+char(39)+')'  
	             SELECT @SQLSTR=@SQLSTR+'          order by  I.BANKID                '    
------------------------------------------------------------------------
--		       print   @SQLSTR

		EXEC(@SQLSTR)








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG















CREATE PROCEDURE [BANK_CACULATOR_YYYYMM ]  (
	@BANKID  varchar(30),
	@YYYYMM  varchar(6)    )
AS 
 
declare @INOUTFLAG NUMERIC(20,10)
declare @INAMOUNT  NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @SUMBAMOUNT NUMERIC(20,10)            ---本期期初总金额
 
BEGIN

            select    @SUMBAMOUNT=isnull(BAMOUNT,0)   FROM   BANKBILLFlow  where    (rtrim(BANKID) = @BANKID) 
						  and (rtrim(YYYYMM) = @YYYYMM) 	and   ( YYYYMMBILL=0   )  
                                       -------以上是期初数据
----------------------------------------------------------------
	    declare BANK_CACULATOR Cursor for Select  BANKID , isnull(INAMOUNT,0) as INAMOUNT, INOUTFLAG, isnull(EAMOUNT,0) as EAMOUNT 
	                  from BANKBILLFlow   where (rtrim(YYYYMM) >= @YYYYMM)  AND ( BANKID=@BANKID)   and   ( YYYYMMBILL=1   )  
             		      ORDER BY BILLDATE,ID

	    Open BANK_CACULATOR

	    fetch BANK_CACULATOR into @BANKID,@INAMOUNT,@INOUTFLAG,@EAMOUNT


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
		 select    @SUMBAMOUNT=@SUMBAMOUNT+@INAMOUNT*@INOUTFLAG

	         	 UPDATE   BANKBILLFLOW  set   EAMOUNT=@SUMBAMOUNT      WHERE CURRENT OF  BANK_CACULATOR

		    fetch BANK_CACULATOR into @BANKID,@INAMOUNT,@INOUTFLAG,@EAMOUNT
 
	    END           ------- BANK_CACULATOR  WHILE

	    close BANK_CACULATOR
	    deallocate BANK_CACULATOR

-----------------------------------------------------------------------------------------------------------------------------------------------------------


END









----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG

















--------------------------------------------------------------------

CREATE PROCEDURE BETWEEN_CURR_YYYYMM  
                 (
                  @BILLDATE DATEtime,
                  @flagreturn int output,     ---返回记帐成功  -- 0 不在此会计期间  --1 在会计期间
                  @BillYYYYMMreturn VARCHAR(10) output     ---返回记帐成功  -- 0 不在此会计期间  --1 在会计期间
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     

declare @MINBILLDATE DATEtime
declare @MAXBILLDATE DATEtime
declare @PRODUCTDATE DATEtime
declare @B_ID INTEGER
declare @STOREHSFS   INTEGER

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

     select @flagreturn = 1     

   declare  @PREV_YYYYMM          varchar(6)  -- 上一个会计年月
   declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
	if substring(@YYYYMM,5,2) = '12'  --- 如果当前会计月等于最大的会计月，将需要转入下年的的第一个会计年月
	begin
	    set @Next_YYYYMM   = convert(varchar,convert(int,substring(@YYYYMM,1,4))+1) +'01'  
	end
	else
	begin
	    set @Next_YYYYMM   = substring(@YYYYMM,1,4) +substring('00',1,2-len(convert(varchar,convert(int,substring(@YYYYMM,5,2))+1)))+convert(varchar,convert(int,substring(@YYYYMM,5,2))+1)
	end

	if substring(@YYYYMM,5,2) = '01'  --- 如果当前会计月等于最大的会计月，将需要转入下年的的第一个会计年月
	begin
	    set @PREV_YYYYMM   = convert(varchar,convert(int,substring(@YYYYMM,1,4))-1) +'12'  
	end
	else
	begin
	    set @PREV_YYYYMM   = substring(@YYYYMM,1,4) +substring('00',1,2-len(convert(varchar,convert(int,substring(@YYYYMM,5,2))-1)))+convert(varchar,convert(int,substring(@YYYYMM,5,2))-1)
	end

	declare @YYYYMMFS INTEGER
	declare @YYYYMMFSDATE  INTEGER
	declare @Billday  INTEGER

	       SELECT    @YYYYMMFS =(SELECT  YYYYMMFS   FROM   ACCINFO    WHERE   GUID='0001' )    
                IF @YYYYMMFS=1
	  BEGIN
		     SET  @MINBillDate = CONVERT(DATEtime,@YYYYMM+'01')
		     SET  @MAXBillDate =CONVERT(DATEtime,@Next_YYYYMM+'01')
		     set @BillYYYYMMreturn=convert(varchar,DATEPART(year,@BillDate))+substring('00',1,2-len(convert(varchar,DATEPART(month,@BillDate))))+convert(varchar,DATEPART(month,@BillDate))
	  END
               ELSE
               BEGIN
	       SELECT    @YYYYMMFSDATE =(SELECT  YYYYMMFSDATE   FROM   ACCINFO    WHERE   GUID='0001' )    
       
	     SET  @MINBillDate =DATEADD(day, @YYYYMMFSDATE, CONVERT(DATEtime,@PREV_YYYYMM+'01'))
	     SET  @MAXBillDate =DATEADD(day, @YYYYMMFSDATE, CONVERT(DATEtime,@YYYYMM+'01'))
        	SELECT @Billday =DATEPART(day, @BillDate)
		if @Billday> @YYYYMMFSDATE  -----分界线
		begin
		     set @BillYYYYMMreturn=convert(varchar,DATEPART(year,DATEADD(month,1,@BillDate)))+substring('00',1,2-len(convert(varchar,DATEPART(month,DATEADD(month,1,@BillDate)))))+convert(varchar,DATEPART(month,DATEADD(month,1,@BillDate)))
		end
		else
		begin
		     set @BillYYYYMMreturn=convert(varchar,DATEPART(year,@BillDate))+substring('00',1,2-len(convert(varchar,DATEPART(month,@BillDate))))+convert(varchar,DATEPART(month,@BillDate))
		end



	 END

----      IF (@BillDate<@MINBillDate)  OR (@BillDate>=@MAXBillDate)
----可以记账当前会计期间以后的单据
      IF (@BillDate<@MINBillDate)  
      BEGIN
      set @flagreturn = 0
      RETURN
      END








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













--------------------------------------------------------------------
--Create by li fa zheng  2004/05/11            
--------------------------------------------------------------------

CREATE PROCEDURE [Bs_Update_AREATree] (@gt_no varchar(8))     --APSOFTENCRYPTION       WITH ENCRYPTION
AS

--declare local variables needed
declare @PLCODE varchar(8)
declare @PPrevno varchar(8)

declare @DIndirect_no varchar(8)
declare @DDirect_no varchar(8)
declare @DSelf_no varchar(8)

declare @CLCODE varchar(8)
declare @CPrevno varchar(8)
declare @CPrevPrevno varchar(8)

declare @temp_no varchar(8)


--find the insert or update record in AREA
select @PLCODE=(LCODE), @PPrevno=(Prevno)
from AREA
where LCODE=@gt_no

--delete the old record in the AREAtree 
while exists(select * from AREAtree where self_no=@PLCODE)
begin
  select @DIndirect_no=(Indirect_no), @DDirect_no=(Direct_no), @DSelf_no=(Self_no) from AREAtree where self_no=@PLCODE 
  delete from AREAtree where (Indirect_no=@DIndirect_no) and (Direct_no=@DDirect_no) and (Self_no=@DSelf_no)
end

--insert into AREAtree

insert into AREATree (indirect_no, direct_no, self_no) 
  values (@PLCODE, @PLCODE, @PLCODE)
set @temp_no=@PLCODE

if @PPrevno='0000'
begin
  insert into AREATree (indirect_no, direct_no, self_no) 
    values ('000000', '000000', @PLCODE)  
end
else
begin
  while exists(select * from AREA where (LCODE=@temp_no))
  begin
    select @CLCODE=(LCODE), @CPrevno=(Prevno) from AREA where (LCODE=@temp_no)

    insert into AREATree (indirect_no, direct_no, self_no) 
      values (@CPrevno, @PPrevno, @PLCODE)  

    set @temp_no=@CPrevNo 
  end
end
  







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













--------------------------------------------------------------------
--Create by li fa zheng  2004/05/11             
--------------------------------------------------------------------

CREATE PROCEDURE [Bs_Update_GoodsTypeTree] (@gt_no varchar(8))   --APSOFTENCRYPTION       WITH ENCRYPTION
AS

--declare local variables needed
declare @PLCODE varchar(8)
declare @PPrevno varchar(8)

declare @DIndirect_no varchar(8)
declare @DDirect_no varchar(8)
declare @DSelf_no varchar(8)

declare @CLCODE varchar(8)
declare @CPrevno varchar(8)
declare @CPrevPrevno varchar(8)

declare @temp_no varchar(8)


--find the insert or update record in goodstype
select @PLCODE=(LCODE), @PPrevno=(Prevno)
from GoodsType
where LCODE=@gt_no

--delete the old record in the goodstypetree 
while exists(select * from goodstypetree where self_no=@PLCODE)
begin
  select @DIndirect_no=(Indirect_no), @DDirect_no=(Direct_no), @DSelf_no=(Self_no) from goodstypetree where self_no=@PLCODE 
  delete from goodstypetree where (Indirect_no=@DIndirect_no) and (Direct_no=@DDirect_no) and (Self_no=@DSelf_no)
end

--insert into goodstypetree

insert into GoodsTypeTree (indirect_no, direct_no, self_no) 
  values (@PLCODE, @PLCODE, @PLCODE)
set @temp_no=@PLCODE

if @PPrevno='0000'
begin
  insert into GoodsTypeTree (indirect_no, direct_no, self_no) 
    values ('000000', '000000', @PLCODE)  
end
else
begin
  while exists(select * from goodstype where (LCODE=@temp_no))
  begin
    select @CLCODE=(LCODE), @CPrevno=(Prevno) from goodstype where (LCODE=@temp_no)

    insert into GoodsTypeTree (indirect_no, direct_no, self_no) 
      values (@CPrevno, @PPrevno, @PLCODE)  

    set @temp_no=@CPrevNo 
  end
end
  







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













--------------------------------------------------------------------
--Create by li fa zheng  2004/05/11            
--------------------------------------------------------------------

CREATE PROCEDURE [Bs_Update_INTYPETree] (@gt_no varchar(8))     --APSOFTENCRYPTION       WITH ENCRYPTION
AS

--declare local variables needed
declare @PLCODE varchar(8)
declare @PPrevno varchar(8)

declare @DIndirect_no varchar(8)
declare @DDirect_no varchar(8)
declare @DSelf_no varchar(8)

declare @CLCODE varchar(8)
declare @CPrevno varchar(8)
declare @CPrevPrevno varchar(8)

declare @temp_no varchar(8)


--find the insert or update record in INTYPE
select @PLCODE=(LCODE), @PPrevno=(Prevno)
from INTYPE
where LCODE=@gt_no

--delete the old record in the INTYPEtree 
while exists(select * from INTYPEtree where self_no=@PLCODE)
begin
  select @DIndirect_no=(Indirect_no), @DDirect_no=(Direct_no), @DSelf_no=(Self_no) from INTYPEtree where self_no=@PLCODE 
  delete from INTYPEtree where (Indirect_no=@DIndirect_no) and (Direct_no=@DDirect_no) and (Self_no=@DSelf_no)
end

--insert into INTYPEtree

insert into INTYPETree (indirect_no, direct_no, self_no) 
  values (@PLCODE, @PLCODE, @PLCODE)
set @temp_no=@PLCODE

if @PPrevno='0000'
begin
  insert into INTYPETree (indirect_no, direct_no, self_no) 
    values ('000000', '000000', @PLCODE)  
end
else
begin
  while exists(select * from INTYPE where (LCODE=@temp_no))
  begin
    select @CLCODE=(LCODE), @CPrevno=(Prevno) from INTYPE where (LCODE=@temp_no)

    insert into INTYPETree (indirect_no, direct_no, self_no) 
      values (@CPrevno, @PPrevno, @PLCODE)  

    set @temp_no=@CPrevNo 
  end
end
  







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













--------------------------------------------------------------------
--Create by li fa zheng  2004/05/11            
--------------------------------------------------------------------

CREATE PROCEDURE [Bs_Update_OUTTYPETree] (@gt_no varchar(8))     --APSOFTENCRYPTION       WITH ENCRYPTION
AS

--declare local variables needed
declare @PLCODE varchar(8)
declare @PPrevno varchar(8)

declare @DIndirect_no varchar(8)
declare @DDirect_no varchar(8)
declare @DSelf_no varchar(8)

declare @CLCODE varchar(8)
declare @CPrevno varchar(8)
declare @CPrevPrevno varchar(8)

declare @temp_no varchar(8)


--find the insert or update record in OUTTYPE
select @PLCODE=(LCODE), @PPrevno=(Prevno)
from OUTTYPE
where LCODE=@gt_no

--delete the old record in the OUTTYPEtree 
while exists(select * from OUTTYPEtree where self_no=@PLCODE)
begin
  select @DIndirect_no=(Indirect_no), @DDirect_no=(Direct_no), @DSelf_no=(Self_no) from OUTTYPEtree where self_no=@PLCODE 
  delete from OUTTYPEtree where (Indirect_no=@DIndirect_no) and (Direct_no=@DDirect_no) and (Self_no=@DSelf_no)
end

--insert into OUTTYPEtree

insert into OUTTYPETree (indirect_no, direct_no, self_no) 
  values (@PLCODE, @PLCODE, @PLCODE)
set @temp_no=@PLCODE

if @PPrevno='0000'
begin
  insert into OUTTYPETree (indirect_no, direct_no, self_no) 
    values ('000000', '000000', @PLCODE)  
end
else
begin
  while exists(select * from OUTTYPE where (LCODE=@temp_no))
  begin
    select @CLCODE=(LCODE), @CPrevno=(Prevno) from OUTTYPE where (LCODE=@temp_no)

    insert into OUTTYPETree (indirect_no, direct_no, self_no) 
      values (@CPrevno, @PPrevno, @PLCODE)  

    set @temp_no=@CPrevNo 
  end
end
  







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













CREATE PROCEDURE [dbo].[CGRKGoodsPrice_Update]   --APSOFTENCRYPTION       WITH ENCRYPTION
as
declare @CODE00   [varchar] (25)   
declare @SFLAG  INTEGER
declare @BILLTYPE   INTEGER
declare @NewBILLDATE DATEtime
declare @GOODSID  varchar(20)
declare @MAXITEMNO  varchar(20)
declare @MAXITEMNO_PREV  varchar(20)
declare @DEQTY NUMERIC(20,6)
declare @MEQTY NUMERIC(20,6)
declare @DEQTY_CURR NUMERIC(20,6)
declare @MEQTY_CURR NUMERIC(20,6)

begin
--------计算所有仓库的库存
     exec Store_Yue_JiSuan
--------插入临时表 

Create Table #TEMP1 
      (   GOODSID  varchar(10) ,
	[DEQTY] NUMERIC(20,6)  NULL ,
	[MEQTY] NUMERIC(20,6)  NULL ,
		)
		
     insert into  #TEMP1    
     Select GOODsID,EQTY as DEQTY,UNITQTY as MEQTY from Store_GoodsID_YUE where EQTY <>0  OR unitQTY <>0

     update  CGRKGoodsPrice  set  DEQTY =  0,MEQTY=0  where isnull(DEQTY,0)<>0 OR isnull(MEQTY,0)<>0
     
     declare CGRK_Cur Cursor READ_ONLY for Select  GOODSID ,ISNULL(DEQTY,0),ISNULL(MEQTY,0) from #TEMP1     ORDER BY GoodsID

	    Open CGRK_Cur

	    fetch CGRK_Cur into @GOODSID ,@DEQTY,@MEQTY 


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	                       
	          select  @MAXITEMNO=max(ITEMNO) from CGRKGoodsPrice where GOODSID=@GOODSID
	          while (@MAXITEMNO is not null) and (@DEQTY>0 OR @MEQTY>0)
	          begin
	                  Select @DEQTY_CURR=quantity,@MEQTY_CURR=unitqty from CGRKGoodsPrice where GOODSID=@GOODSID  and ITEMNO=@MAXITEMNO 
	                  Select @DEQTY=@DEQTY-@DEQTY_CURR   
	                  Select @MEQTY=@MEQTY-@MEQTY_CURR   
	                  Select @MAXITEMNO_PREV=@MAXITEMNO
	            IF  @DEQTY<>-9999999999
	            begin
	                  if  @DEQTY < 0 
                      BEGIN 
 		                   UPDATE   CGRKGoodsPrice    set    DEQTY=@DEQTY+@DEQTY_CURR where GOODSID=@GOODSID  and ITEMNO=@MAXITEMNO              			         
 		                   select @DEQTY=-9999999999   -----小于0就不计算了
                      END
                      ELSE
                      BEGIN 
 		                   UPDATE   CGRKGoodsPrice    set    DEQTY=quantity where GOODSID=@GOODSID  and ITEMNO=@MAXITEMNO              			         
                      END
                end
	            IF  @DEQTY<>-9999999999
	            begin                     
	                  if  @MEQTY < 0 
                      BEGIN 
 		                   UPDATE   CGRKGoodsPrice    set    MEQTY=@MEQTY+@MEQTY_CURR where GOODSID=@GOODSID  and ITEMNO=@MAXITEMNO              			         
 		                   select @MEQTY=-9999999999
                      END
                      ELSE
                      BEGIN 
 		                   UPDATE   CGRKGoodsPrice    set    MEQTY=unitqty where GOODSID=@GOODSID  and ITEMNO=@MAXITEMNO              			         
                      END
                      
	                 select  @MAXITEMNO=max(ITEMNO) from CGRKGoodsPrice where GOODSID=@GOODSID and ITEMNO < @MAXITEMNO_PREV
                end
              END    ----end---while (@MAXITEMNO is not null) and (@DEQTY>0 OR @MEQTY>0)

	    fetch CGRK_Cur into @GOODSID ,@DEQTY,@MEQTY 
 

	    END           ------- CGRK_Cur  WHILE

	    close CGRK_Cur
	    deallocate CGRK_Cur

-----------------------------------------------------------------------------------------------------------------------------------------------------------
drop table #TEMP1

     
     

end


----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG















--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE CLIENTINOUTMXBREP(@CLIENTID varchar(8) ,                        -----如果为0000则全部仓库
                                                                                            @Begin_Date   varchar(10) ,
                                                                                           @End_date   varchar(10) 
                        
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @end_dateAddone  datetime,
        @MAXBILLDATE  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8),
        @WHERESTING   varchar(1800)

declare @CLIENTNAME  varchar(50)
declare @CLIENTSTR  varchar(50)
declare @BumenID  varchar(50)

declare @ID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare  @BILLTYPE  INTEGER
declare  @INOUTFLAG  INTEGER
declare @BILLCODE  nvarchar(50)
declare @BILLDATE  datetime
declare @BILLTYPENAME  nvarchar(50)
declare @INAMOUNT NUMERIC(20,10)
declare @OUTAMOUNT NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @EAMOUNTPREV NUMERIC(20,10)
---//==========
declare @BAMOUNT NUMERIC(20,10)
declare @MAXID  nvarchar(50)

                   set @now_date=(select   max(billDATE)   FROM CLIENTbillflow)

                          IF @now_date IS NULL
		BEGIN
			set @now_date='2029-10-12'         ----以后纠正此特殊值，此值为调试程序用
		END
                       

                          SELECT    @WHERESTING  = '  AND     BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+ @End_date+char(39) 
                          SELECT    @CLIENTSTR  = '  AND     CLIENTID ='+char(39)+@CLIENTID+char(39)


     

Create Table #temptable10
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL 
		)

Create Table #temptable1
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
    INOUTFLAG  INTEGER
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   ID , BILLID,BILLTYPE,BILLCODE,BILLDATE,BILLTYPE,  '
           SELECT  @SQLSTR = @SQLSTR+'INAMOUNT,OUTAMOUNT,EAMOUNT ,INOUTFLAG '
           SELECT  @SQLSTR = @SQLSTR+'  from CLIENTbillflow   where yyyymmbill=1    '  + @WHERESTING+@CLIENTSTR 
           SELECT  @SQLSTR = @SQLSTR+'  order by id '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
    INOUTFLAG  INTEGER ,
   BuMenID  nvarchar(50)  NULL
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (Select  ID,BILLID,BILLTYPE, BILLCODE,BILLDATE,BILLTYPENAME,
                                                     isnull(INAMOUNT,0) as INAMOUNT ,  isnull(OUTAMOUNT,0) as OUTAMOUNT ,
                                                     isnull(EAMOUNT,0) as EAMOUNT   from  #temptable1        )
                 begin
	    declare INOUTMXBREP Cursor for Select  ID,BILLID,BILLTYPE , BILLCODE,BILLDATE,BILLTYPENAME,
                                                       isnull(INAMOUNT,0) as INAMOUNT ,   isnull(OUTAMOUNT,0) as OUTAMOUNT ,
                                                     isnull(EAMOUNT,0) as EAMOUNT ,INOUTFLAG  from  #temptable1         ORDER BY BILLDATE,ID
	    Open INOUTMXBREP

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INAMOUNT,@OUTAMOUNT,@EAMOUNT,@INOUTFLAG

                 SELECT  @CLIENTNAME=NAME   FROM CLIENT  WHERE CLIENTID=@CLIENTID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME         )
                                           VALUES  (@COUNTID, @CLIENTNAME)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                           select @MAXBILLDATE=MAX(BILLDATE) FROM CLIENTbillflow   WHERE  CLIENTID=@CLIENTID   AND     BILLDATE  < @begin_date     AND YYYYMMBILL=1
                           SELECT  @MAXID=MAX(ID)  FROM CLIENTbillflow  WHERE  CLIENTID=@CLIENTID     AND  BILLDATE=@MAXBILLDATE   AND YYYYMMBILL=1
                                         IF @MAXID IS NULL
 			BEGIN
			SET  @BAMOUNT=0
			END
                                        ELSE
			BEGIN
	                           SELECT @BAMOUNT=EAMOUNT   FROM   CLIENTbillflow  WHERE ID=@MAXID
			END
                                                              
                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID , '期初结存',@BAMOUNT)
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
                       SELECT  @BILLTYPENAME=NAME FROM  BILLNAME  WHERE @BILLTYPENAME=BILLTYPEID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF @INOUTFLAG=1 
		BEGIN
			SELECT @INAMOUNT=@INAMOUNT
			SELECT @OUTAMOUNT=0
		END
		IF @INOUTFLAG=-1 
		BEGIN
			SELECT @OUTAMOUNT=@INAMOUNT
			SELECT @INAMOUNT=0
		END

-----------------2012.08.01增加部门
                 select @bumenID=bumenID from ViewBILL where BILLID=@BillID AND BILLTYPE=@BILLTYPE

-----------------

                          INSERT    INTO   #temptable2  (ID,BILLID,BILLTYPE, BILLCODE,BILLDATE,BILLTYPENAME,
                                                               INAMOUNT,OUTAMOUNT,EAMOUNT,bumenID)
                                           VALUES  (@COUNTID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INAMOUNT,@OUTAMOUNT,@EAMOUNT,@bumenID)
 		    SET @EAMOUNTPREV=@EAMOUNT

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INAMOUNT,@OUTAMOUNT,@EAMOUNT,@INOUTFLAG
 

	    END           ------- INOUTMXBREP  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期末结存',@EAMOUNT)

	    close INOUTMXBREP
	    deallocate INOUTMXBREP
        end     ------------  if exists
---------------------------
---------解决当前仓库本期间未发生业务的货品
--                  delete    #temptable1
            ELSE
            BEGIN

                           select @MAXBILLDATE=MAX(BILLDATE) FROM CLIENTbillflow   WHERE  CLIENTID=@CLIENTID   AND     BILLDATE  < @begin_date     AND YYYYMMBILL=1
                           SELECT  @MAXID=MAX(ID)  FROM CLIENTbillflow  WHERE  CLIENTID=@CLIENTID     AND  BILLDATE=@MAXBILLDATE   AND YYYYMMBILL=1


	             	  SELECT    @ID=ID,@EAMOUNT=EAMOUNT    FROM  CLIENTbillflow  WHERE    ID = @MAXID

                 SELECT @CLIENTNAME=NAME   FROM CLIENT  WHERE CLIENTID=@CLIENTID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME         )
                                           VALUES  (@COUNTID,@CLIENTNAME)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                                                              
                          INSERT    INTO   #temptable2  (ID , BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期初结存',@EAMOUNT)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期末结存',@EAMOUNT)

---------------------------
	END




--------------------------

 SELECT *  FROM #temptable2         ORDER BY ID







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG

























--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE CLIENTXSCKMXB( @WHERESTING   varchar(1800)
                       
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8)

declare @GOODSNAME  varchar(50)
declare @CLIENTNAME  varchar(50)

declare @ID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @BILLTYPE  INT
declare @PRICETYPE  INT
declare @CaiZhi  varchar(50)
declare @SpecNameD  varchar(50)
declare @ChanDi  varchar(50)
declare @FuZhuQTY  varchar(50)
declare @CLIENTID  nvarchar(50)
declare @GOODSCODE  nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLCODE  nvarchar(50)
declare @BILLDATE  datetime
declare @BILLDATE00  datetime
declare @CLIENTID00  nvarchar(50)
declare @PRICE NUMERIC(20,10)
declare @QUANTITY NUMERIC(20,10)
declare @TAXRATE  NUMERIC(20,10)
declare @DISC  NUMERIC(20,10)
declare @UNITPRICE NUMERIC(20,10)
declare @UNITQTY NUMERIC(20,10)
declare @SUMAMT NUMERIC(20,10)
declare @SUMTAXAMT NUMERIC(20,10)
declare @SUMDayAMT NUMERIC(20,10)
declare @SUMDayTAXAMT NUMERIC(20,10)
declare @AMT NUMERIC(20,10)
declare @TAXAMT NUMERIC(20,10)
declare @ClientFlag smallint 
declare @ClientFlag00 smallint 
    

Create Table #temptable1
      (   CLIENTID varchar(50)  NULL,
       GOODSID  varchar(10) ,
       GOODScode  varchar(30) ,
      BILLID  nvarchar(50)  NULL,
      BILLTYPE INT,
	[PRICE] NUMERIC(20,10)  NULL ,
	[DISC] NUMERIC(20,10)  NULL ,
	[QUANTITY] NUMERIC(20,10)  NULL ,
	[TAXRATE]NUMERIC(20,10)  NULL ,
	BILLDATE DATEtime,
	[UNITPRICE] NUMERIC(20,10)  NULL ,
	[UNITQTY]NUMERIC(20,10)  NULL ,
		     PRICETYPE  INT ,
	[AMT]NUMERIC(20,10)  NULL ,
	[TAXAMT]NUMERIC(20,10)  NULL, 
	[ClientFlag]smallint  NULL ,
       ChanDi  varchar(30) ,
       FuZhuQTY  varchar(30) ,
       SpecNameD varchar(30) ,
       CaiZhi  varchar(30) 
	)

           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   CLIENTID,VIEWXSCK.GOODSID, GOODS.CODE AS GOODSCODE,BILLID,BILLTYPE,PRICE,DISC,QUANTITY,TAXRATE,BILLDATE '
           SELECT  @SQLSTR = @SQLSTR+'  ,UNITPRICE,UNITQTY,PRICETYPE,AMT,TAXAMT,ClientFlag,ChanDi,FuZhuQTY,SpecNameD,CaiZhi  from VIEWXSCK  ,GOODS  '  + @WHERESTING +'  AND  VIEWXSCK.GOODSID = GOODS.GOODSID'
           SELECT  @SQLSTR = @SQLSTR+'  order by CLIENTID,VIEWXSCK.GOODSID,BILLDATE,BILLID '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   GOODSNAME  nvarchar(50)  NULL,
   GOODSCODE  nvarchar(50)  NULL,
   UNIT  nvarchar(10)  NULL,
	[QUANTITY] NUMERIC(20,10)  NULL ,
	[PRICE] NUMERIC(20,10)  NULL ,
	[TAXRATE]NUMERIC(20,10)  NULL ,
	[AMT]NUMERIC(20,10)  NULL ,
	[TAXAMT]NUMERIC(20,10)  NULL, 
	  priceTYPENAME  nvarchar(10)  NULL,
       ChanDi  varchar(30) ,
       FuZhuQTY  varchar(30) ,
       SpecNameD varchar(30) ,
       CaiZhi  varchar(30) 
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (select  CLIENTID, GOODSID, BILLID,PRICE,DISC,QUANTITY,TAXRATE   from  #temptable1        )
                 begin
	    declare XSCKMXB_CLIENT Cursor for select  CLIENTID, GOODSID, BILLID,PRICE,DISC,QUANTITY,TAXRATE,BILLTYPE,DISC ,UNITPRICE,UNITQTY,PRICETYPE,AMT,TAXAMT,ClientFlag,ChanDi,FuZhuQTY,CaiZhi,SpecNameD,BILLDATE    from  #temptable1  
                                                            ORDER BY  CLIENTID,ClientFlag,BILLDATE,GOODSCODE, BILLID
	    Open XSCKMXB_CLIENT

	    fetch XSCKMXB_CLIENT into   @CLIENTID,@GOODSID,@BILLID,@PRICE,@DISC,@QUANTITY,@TAXRATE,@BILLTYPE,@DISC ,@UNITPRICE,@UNITQTY,@PRICETYPE,@AMT,@TAXAMT,@ClientFlag,@ChanDi,@FuZhuQTY,@CaiZhi,@SpecNameD,@BILLDATE

                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @CLIENTNAME =(SELECT NAME   FROM ViewCLIENT  WHERE CLIENTID=@CLIENTID  and CLIENTFlag=@CLIENTFlag)
                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)

                 SELECT  @CLIENTID00=@CLIENTID
		 SELECT  @CLIENTFlag00=@CLIENTFlag
                 SELECT  @BILLDATE00=@BILLDATE

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                                           VALUES  (@COUNTID,@CLIENTNAME)
		SELECT @SUMAMT=0
		SELECT @SUMTAXAMT=0
		SELECT @SUMDayAMT=0
		SELECT @SUMDayTAXAMT=0
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID



		IF  not( @BILLDATE00=@BILLDATE)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,AMT,TAXAMT)
                                           VALUES  (@COUNTID, '按日小计',@SUMDayAMT,@SUMDayTAXAMT)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

----		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
----			         SELECT  @CLIENTNAME =(SELECT NAME   FROM ViewCLIENT  WHERE CLIENTID=@CLIENTID  and CLIENTFlag=@CLIENTFlag)
----		                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @BILLDATE00=@BILLDATE


			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                           	                VALUES  (@COUNTID,@CLIENTNAME)
				SELECT @SUMDayAMT=0
				SELECT @SUMDayTAXAMT=0
		END	






		IF  not( @CLIENTID00 = @CLIENTID AND @CLIENTFlag00=@CLIENTFlag)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,AMT,TAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMAMT,@SUMTAXAMT)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
			         SELECT  @CLIENTNAME =(SELECT NAME   FROM ViewCLIENT  WHERE CLIENTID=@CLIENTID  and CLIENTFlag=@CLIENTFlag)
		                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @CLIENTID00=@CLIENTID
				 SELECT  @CLIENTFlag00=@CLIENTFlag


			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                           	                VALUES  (@COUNTID,@CLIENTNAME)
				SELECT @SUMAMT=0
				SELECT @SUMTAXAMT=0
				SELECT @SUMDayAMT=0
				SELECT @SUMDayTAXAMT=0
		END	
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
	  			SELECT @UNIT = (SELECT UNIT   FROM GOODS  WHERE GOODSID=@GOODSID)
			IF @BILLTYPE=2
			BEGIN
			   SELECT @BILLCODE=(SELECT CODE   FROM STOREXSCKM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STOREXSCKM  WHERE BILLID=@BILLID)
			END
			IF @BILLTYPE=12
			BEGIN
			   SELECT @BILLCODE=(SELECT CODE   FROM STOREXSTHM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STOREXSTHM  WHERE BILLID=@BILLID)
			END
		                 SELECT  @GOODSNAME=(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @GOODSCODE=(SELECT CODE   FROM GOODS  WHERE GOODSID=@GOODSID)

				IF @PRICETYPE=1 
				BEGIN
			                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,GOODSNAME,GOODSCODE,UNIT, QUANTITY,PRICE,TAXRATE, AMT,TAXAMT,PRICETYPENAME,ChanDi,FuZhuQTY,CaiZhi,SpecNameD)
             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@GOODSNAME,@GOODSCODE,@UNIT,@QUANTITY,@UNITPRICE,@TAXRATE,@AMT,@TAXAMT,'重量',@ChanDi,@FuZhuQTY,@CaiZhi,@SpecNameD)
				END
				IF @PRICETYPE=0
				BEGIN
			                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,GOODSNAME,GOODSCODE,UNIT, QUANTITY,PRICE,TAXRATE, AMT,TAXAMT,PRICETYPENAME,ChanDi,FuZhuQTY,CaiZhi,SpecNameD)
             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@GOODSNAME,@GOODSCODE,@UNIT,@UNITQTY,@UNITPRICE,@TAXRATE,@AMT,@TAXAMT,'数量',@ChanDi,@FuZhuQTY,@CaiZhi,@SpecNameD)
				END
				SELECT @SUMAMT=@SUMAMT+@AMT
				SELECT @SUMTAXAMT=@SUMTAXAMT+@TAXAMT
				SELECT @SUMDayAMT=@SUMDayAMT+@AMT
				SELECT @SUMDayTAXAMT=@SUMDayTAXAMT+@TAXAMT
		
	    fetch XSCKMXB_CLIENT into   @CLIENTID,@GOODSID,@BILLID,@PRICE,@DISC,@QUANTITY,@TAXRATE,@BILLTYPE,@DISC ,@UNITPRICE,@UNITQTY,@PRICETYPE,@AMT,@TAXAMT,@ClientFlag,@ChanDi,@FuZhuQTY,@CaiZhi,@SpecNameD,@BILLDATE
 
	    END           ------- XSCKMXB_CLIENT  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,AMT,TAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMAMT,@SUMTAXAMT)

	    close XSCKMXB_CLIENT
	    deallocate XSCKMXB_CLIENT
        end     ------------  if exists

 SELECT *  FROM #temptable2         ORDER BY ID














----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG







--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE [dbo].[CLIENTXSDDMXB]( @WHERESTING   varchar(1800)
                       
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8)

declare @GOODSNAME  varchar(50)
declare @CLIENTNAME  varchar(50)

declare @ID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @CLIENTID  nvarchar(50)
declare @GOODSCODE  nvarchar(50)
declare @SpecName  nvarchar(50)
declare @ModelName  nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLCODE  nvarchar(50)
declare @BILLTYPE INT
declare @BILLDATE  datetime
declare @CLIENTID00  nvarchar(50)
declare @PRICE NUMERIC(20, 6)
declare @TAXAMT NUMERIC(20, 2)
declare @WCunitQTY NUMERIC(20, 6)
declare @WCquantity NUMERIC(20, 6)
declare @zzunitQTY NUMERIC(20, 6)
declare @zzquantity NUMERIC(20, 6)
declare @WCTAXAMT NUMERIC(20, 6)
declare @TAXRATE  NUMERIC(20, 6)
declare @RATE  NUMERIC(20, 6)
declare @WEITAXAMT NUMERIC(20, 6)
declare @SUMWCTAXAMT NUMERIC(20, 6)
declare @SUMWEITAXAMT NUMERIC(20, 6)
declare @SUMTAXAMT NUMERIC(20, 6)
declare @UNITQTY NUMERIC(20, 6)
declare @quantity NUMERIC(20, 6)
declare @UNITPRICE NUMERIC(20, 6)
declare @DISC NUMERIC(20, 6)
declare    @PRICETYPE int

Create Table #temptable1
      (   CLIENTID varchar(50)  NULL,
       GOODSID  varchar(10) ,
       GOODSCODE  varchar(30) ,
      BILLID  nvarchar(50)  NULL,
      BILLTYPE  INT ,
	[PRICE] NUMERIC(20, 6)  NULL ,
	[UNITQTY] NUMERIC(20, 6)  NULL ,
	[quantity] NUMERIC(20, 6)  NULL ,
	[DISC] NUMERIC(20, 6)  NULL ,
	[TAXRATE]NUMERIC(20, 6)  NULL ,
	   BILLDATE  datetime  NULL,
	[UNITPRICE] NUMERIC(20, 6)  NULL ,
	[WCunitQTY]NUMERIC(20, 6)  NULL ,
	[WCquantity]NUMERIC(20, 6)  NULL ,
	[zzunitQTY]NUMERIC(20, 6)  NULL ,
	[zzquantity]NUMERIC(20, 6)  NULL ,
	[TAXAMT]NUMERIC(20, 2)  NULL, 
	[PRICETYPE]    int  NULL, 
	       DETAILBILLFLOWID  varchar(10) 
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   VIEWXSDD.CLIENTID,VIEWXSDD.GOODSID,GOODS.CODE AS GOODSCODE, BILLID,BILLTYPE,PRICE,UNITQTY,quantity,DISC,TAXRATE,BILLDATE '
           SELECT  @SQLSTR = @SQLSTR+' ,UNITPRICE,WCunitQTY,WCquantity,zzunitQTY,zzquantity,TAXAMT,PRICETYPE,DETAILBILLFLOWID  from VIEWXSDD   ,GOODS  '  + @WHERESTING +'  AND  VIEWXSDD.GOODSID = GOODS.GOODSID'
           SELECT  @SQLSTR = @SQLSTR+'  order by VIEWXSDD.CLIENTID,VIEWXSDD.GOODSID,BILLDATE,DETAILBILLFLOWID '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
	   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   GOODSNAME  nvarchar(50)  NULL,
   GOODSCODE  nvarchar(50)  NULL,
      SpecName  nvarchar(50)  NULL,
   ModelName  nvarchar(50)  NULL,
UNIT  nvarchar(10)  NULL,
	[UNITQTY] NUMERIC(20, 6)  NULL ,
	[quantity] NUMERIC(20, 6)  NULL ,
	[TAXAMT]NUMERIC(20, 2)  NULL, 
	[WCunitQTY] NUMERIC(20, 6)  NULL ,
	[WCquantity] NUMERIC(20, 6)  NULL ,
	[zzunitQTY] NUMERIC(20, 6)  NULL ,
	[zzquantity] NUMERIC(20, 6)  NULL ,
	[WCTAXAMT]NUMERIC(20, 6)  NULL ,
	[WEIunitQTY] NUMERIC(20, 6)  NULL ,
	[WEIquantity] NUMERIC(20, 6)  NULL ,
	[WEITAXAMT]NUMERIC(20, 6)  NULL 
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (select  CLIENTID, GOODSID, BILLID,PRICE,UNITQTY,TAXRATE,BILLTYPE   from  #temptable1        )
                 begin
	    declare XSDDMXB_CLIENT Cursor for select  CLIENTID, GOODSID, BILLID,PRICE,UNITQTY,quantity,TAXRATE,BILLTYPE ,DISC,UNITPRICE,WCunitQTY,WCquantity, zzunitQTY,zzquantity,TAXAMT,PRICETYPE  from  #temptable1  
---                                                            ORDER BY  CLIENTID,  BILLDATE,DETAILBILLFLOWID,GOODSCODE
                                                            ORDER BY  CLIENTID,  BILLDATE,BILLID,GOODSCODE
	    Open XSDDMXB_CLIENT

	    fetch XSDDMXB_CLIENT into   @CLIENTID,@GOODSID,@BILLID,@PRICE,@UNITQTY,@quantity,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@WCunitQTY,@WCquantity,@zzunitQTY,@zzquantity,@TAXAMT,@PRICETYPE

                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @CLIENTNAME =(SELECT NAME   FROM CLIENT  WHERE CLIENTID=@CLIENTID)
                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)

                 SELECT  @CLIENTID00=@CLIENTID

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                                           VALUES  (@COUNTID,@CLIENTNAME)
		SELECT @SUMWCTAXAMT=0
		SELECT @SUMTAXAMT=0
		SELECT @SUMWEITAXAMT=0
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF  not( @CLIENTID00 = @CLIENTID)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,WCTAXAMT,TAXAMT,WEITAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMWCTAXAMT,@SUMTAXAMT,@SUMWEITAXAMT)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @CLIENTNAME =(SELECT NAME   FROM CLIENT  WHERE CLIENTID=@CLIENTID)
		                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @CLIENTID00=@CLIENTID


			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                           	                VALUES  (@COUNTID,@CLIENTNAME)
				SELECT @SUMWCTAXAMT=0
				SELECT @SUMTAXAMT=0
				SELECT @SUMWEITAXAMT=0
		END	
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

				--SELECT @RATE =RATE  FROM GOODSUNIT  WHERE GOODSID=@GOODSID AND UNITID=@UNITID

	  			SELECT @UNIT = (SELECT UNIT   FROM GOODS  WHERE GOODSID=@GOODSID)
				
			   SELECT @BILLCODE=(SELECT CODE   FROM STOREXSDDM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STOREXSDDM  WHERE BILLID=@BILLID)
               SELECT  @GOODSCODE=CODE,@GOODSNAME=Name,@SpecName=SpecName,@ModelName=ModelName     FROM GOODS  WHERE GOODSID=@GOODSID
		               if @PRICETYPE=1
		               begin  
		                 SET @WEITAXAMT=Round(ISNULL(@DISC,100)*0.01*(ISNULL(@quantity,0)-ISNULL(@WCquantity,0)-ISNULL(@zzquantity,0))*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
		                 SET @WCTAXAMT=Round(ISNULL(@DISC,100)*0.01*ISNULL(@WCquantity,0)*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
					   end
					   else
					   begin
		                 SET @WEITAXAMT=Round(ISNULL(@DISC,100)*0.01*(ISNULL(@unitqty,0)-ISNULL(@WCunitqty,0)-ISNULL(@zzunitqty,0))*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
		                 SET @WCTAXAMT=Round(ISNULL(@DISC,100)*0.01*ISNULL(@WCunitqty,0)*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
					   end
		                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,GOODSNAME,GOODSCODE,SpecName,ModelName,UNIT, UNITQTY,quantity,TAXAMT,WCunitQTY,WCquantity,zzunitQTY,zzquantity,WCTAXAMT,WEIunitQTY,WEIquantity,WEITAXAMT)
             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@GOODSNAME,@GOODSCODE,@SpecName,@ModelName,@UNIT,@UNITQTY,@quantity,
					                     @TAXAMT,
					                     ISNULL(@WCunitQTY,0) ,
					                     ISNULL(@WCquantity,0) ,
					                     ISNULL(@zzunitQTY,0) ,
					                     ISNULL(@zzquantity,0) ,					@WCTAXAMT,
					                      @UNITQTY-ISNULL(@WCunitQTY,0) -ISNULL(@zzunitQTY,0),
					                      @quantity-ISNULL(@WCquantity,0) -ISNULL(@zzquantity,0),@WEITAXAMT	)

				SELECT @SUMTAXAMT=@SUMTAXAMT+@TAXAMT
				SELECT @SUMWCTAXAMT=@SUMWCTAXAMT+@WCTAXAMT
				SELECT @SUMWEITAXAMT=@SUMWEITAXAMT+@WEITAXAMT
		
	    fetch XSDDMXB_CLIENT into   @CLIENTID,@GOODSID,@BILLID,@PRICE,@UNITQTY,@quantity,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@WCunitQTY,@WCquantity,@zzunitQTY,@zzquantity,@TAXAMT,@PRICETYPE
 
	    END           ------- XSDDMXB_CLIENT  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,WCTAXAMT,TAXAMT,WEITAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMWCTAXAMT,@SUMTAXAMT,@SUMWEITAXAMT)

	    close XSDDMXB_CLIENT
	    deallocate XSDDMXB_CLIENT
        end     ------------  if exists

 SELECT *  FROM #temptable2         ORDER BY ID












----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG


















CREATE PROCEDURE CLIENTYYYYMMDD(  @Begin_Date   varchar(10) ,
                                                                                           @End_date   varchar(10) ,  
                                                                                           @YYYYMM  varchar(8),      --------为当前会计期间
						           @LCODE  varchar(10),             ---如果LCODE  为‘GGGG’表示不对类别进行查询
						           @CLIENTCODE  varchar(20),             ---如果CLIENTCODE  为‘GGGG’表示不对类别进行查询
						           @CLIENTNAME  varchar(20),             ---如果CLIENTNAME  为‘GGGG’表示不对类别进行查询
                                                           @ZEROFLAG   smallint      --------  0  代表 不作为过滤条件

                         
                                                      ) as

Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @WHERESTING   varchar(1800)
                   set @now_date=(select   max(billDATE)   FROM  CLIENTBILLFLOW)
                          IF @now_date IS NULL
		BEGIN
			set @now_date='2009-12-12'         ----以后纠正此特殊值，此值为调试程序用
		END

		if     NOT (@LCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = '  AND   I.CLIENTID IN ( select G.CLIENTID from AREAtree T, CLIENT G where T.indirect_no = '+CHAR(39)+@LCODE+CHAR(39)+ '  AND T.self_no=G.AREAID )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  ='     '
 		END
		if     NOT (@CLIENTCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.CLIENTID IN ( select  CLIENTID from CLIENT   where  CODE LIKE   '+CHAR(39)+'%'+@CLIENTCODE+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  =@WHERESTING+'     '
 		END
		if     NOT (@CLIENTNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.CLIENTID IN ( select  CLIENTID from CLIENT   where  NAME LIKE   '+CHAR(39)+'%'+@CLIENTNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END

--                       print   @WHERESTING
----------------------------------------------------
		SELECT @SQLSTR='	 select  I.CLIENTID,  I.CODE,  I.NAME,       '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0) -(isnull(BN.INAMOUNT,0)- isnull(BN00.INAMOUNT,0)) as BAMOUNT, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(BE.INAMOUNT,0)  AS INAMOUNT   ,ISNULL(BE00.INAMOUNT,0)  AS OUTAMOUNT,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0) -(isnull(BN.INAMOUNT,0)- isnull(BN00.INAMOUNT,0))'
		SELECT @SQLSTR=@SQLSTR+'+ isnull(BE.INAMOUNT,0)-isnull(BE00.INAMOUNT,0) as EAMOUNT' --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from CLIENT  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select CLIENTID,sum(INAMOUNT*INOUTFLAG)  as INAMOUNT  '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from CLIENTBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)
		SELECT @SQLSTR=@SQLSTR+'group by CLIENTID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.CLIENTID = I.CLIENTID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select CLIENTID,sum(BAMOUNT) as BAMOUNT '
		SELECT @SQLSTR=@SQLSTR+' from CLIENTBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by CLIENTID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.CLIENTID = I.CLIENTID  '
------------------------以上部分是取当前库存
		SELECT @SQLSTR=@SQLSTR+'  left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select CLIENTID,sum(INAMOUNT) as INAMOUNT      '
		SELECT @SQLSTR=@SQLSTR+'  from CLIENTBILLFLOW           '
		SELECT @SQLSTR=@SQLSTR+'  where YYYYMMBILL = 1    and BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+ @Now_Date+char(39) +'  AND INOUTFLAG =1'   
		SELECT @SQLSTR=@SQLSTR+' group by CLIENTID'	
		SELECT @SQLSTR=@SQLSTR+' ) as BN on BN.CLIENTID = I.CLIENTID'  
		SELECT @SQLSTR=@SQLSTR+'  left outer join '
		SELECT @SQLSTR=@SQLSTR+'  (  '
		SELECT @SQLSTR=@SQLSTR+'select CLIENTID,sum(INAMOUNT) as INAMOUNT     '
		SELECT @SQLSTR=@SQLSTR+' from CLIENTBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+ @Now_Date +char(39) +' AND INOUTFLAG =-1 '  
		SELECT @SQLSTR=@SQLSTR+' group by CLIENTID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BN00 on BN00.CLIENTID = I.CLIENTID  '
------------------------以上部分为取begin_date到Now_Date的库存
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select CLIENTID,sum(INAMOUNT) as INAMOUNT   '
		SELECT @SQLSTR=@SQLSTR+' from CLIENTBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+@End_Date+char(39)+' AND INOUTFLAG =1 '  
		SELECT @SQLSTR=@SQLSTR+' group by CLIENTID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE on BE.CLIENTID = I.CLIENTID  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select CLIENTID,sum(INAMOUNT) as INAMOUNT   '
		SELECT @SQLSTR=@SQLSTR+' from CLIENTBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+@End_Date +char(39)+'AND INOUTFLAG =-1' 
		SELECT @SQLSTR=@SQLSTR+' group by CLIENTID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE00 on BE00.CLIENTID = I.CLIENTID  '
                SELECT @SQLSTR=@SQLSTR+'  where     I. CLIENTID in (select CLIENTID from CLIENTBILLFLOW where YYYYMM >='+char(39)+@YYYYMM+char(39)+')'  + @WHERESTING 
	        SELECT @SQLSTR=@SQLSTR+'          order by  I.CLIENTID                '    
------------------------------------------------------------------------
--		       print   @SQLSTR


Create Table #temptable2012YS
      (CLIENTID  varchar(10) primary key,
	    CODE  varchar(100) ,
	    NAME  varchar(100) ,
	  BAMOUNT NUMERIC(20,10)  NULL, 
	  INAMOUNT NUMERIC(20,10)  NULL, 
	  OUTAMOUNT NUMERIC(20,10)  NULL, 
	   EAMOUNT NUMERIC(20,10)  NULL 
		)

		INSERT INTO  #temptable2012YS  EXEC(@SQLSTR)


		IF  @ZEROFLAG=0
		BEGIN
                     SELECT *  FROM  #temptable2012YS
		END
		IF  @ZEROFLAG=1
		BEGIN
                     SELECT *  FROM  #temptable2012YS  where EAMOUNT<>0
		END












----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG








CREATE PROCEDURE CLIENTYYYYMMDD_BJ(  @Begin_Date   varchar(10) ,
                                                                                           @End_date   varchar(10) ,  
                                                                                           @YYYYMM  varchar(8)      --------为当前会计期间
                         
                                                      ) as

Declare 
        @end_dateAddone  datetime,
        @LastSKDate  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @ClientID   varchar(20),
        @SQLSTR   varchar(8000),
        @WHERESTING   varchar(1800)
                   set @now_date=(select   max(billDATE)   FROM  CLIENTBILLFLOW)
                          IF @now_date IS NULL
		BEGIN
			set @now_date='2009-12-12'         ----以后纠正此特殊值，此值为调试程序用
		END

			SELECT    @WHERESTING  ='     '

--                       print   @WHERESTING
----------------------------------------------------

CREATE TABLE #CLIENTTMP (
	[CLIENTID] [varchar] (25) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[CODE] [varchar] (50)  NULL ,
	[NAME] [varchar] (100)  NULL ,
	[CREDIT] NUMERIC(20,10) NULL ,
	[QiXianDays] int NULL ,
	[LastSKDate] datetime NULL ,
	[EAMOUNT] NUMERIC(20,10) NULL 
) ON [PRIMARY]





----------------------------------------------------
		SELECT @SQLSTR='	 select  I.CLIENTID,  I.CODE,  I.NAME, I.CREDIT,I.QiXianDays,getdate() AS LastSKDate,    '
--		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0) -(isnull(BN.INAMOUNT,0)- isnull(BN00.INAMOUNT,0)) as BAMOUNT, '   --期初数量
--		SELECT @SQLSTR=@SQLSTR+'ISNULL(BE.INAMOUNT,0)  AS INAMOUNT   ,ISNULL(BE00.INAMOUNT,0)  AS OUTAMOUNT,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0) -(isnull(BN.INAMOUNT,0)- isnull(BN00.INAMOUNT,0))'
		SELECT @SQLSTR=@SQLSTR+'+ isnull(BE.INAMOUNT,0)-isnull(BE00.INAMOUNT,0) as EAMOUNT' --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from CLIENT  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select CLIENTID,sum(INAMOUNT*INOUTFLAG)  as INAMOUNT  '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from CLIENTBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)
		SELECT @SQLSTR=@SQLSTR+'group by CLIENTID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.CLIENTID = I.CLIENTID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select CLIENTID,sum(BAMOUNT) as BAMOUNT '
		SELECT @SQLSTR=@SQLSTR+' from CLIENTBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by CLIENTID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.CLIENTID = I.CLIENTID  '
------------------------以上部分是取当前库存
		SELECT @SQLSTR=@SQLSTR+'  left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select CLIENTID,sum(INAMOUNT) as INAMOUNT      '
		SELECT @SQLSTR=@SQLSTR+'  from CLIENTBILLFLOW           '
		SELECT @SQLSTR=@SQLSTR+'  where YYYYMMBILL = 1    and BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+ @Now_Date+char(39) +'  AND INOUTFLAG =1'   
		SELECT @SQLSTR=@SQLSTR+' group by CLIENTID'	
		SELECT @SQLSTR=@SQLSTR+' ) as BN on BN.CLIENTID = I.CLIENTID'  
		SELECT @SQLSTR=@SQLSTR+'  left outer join '
		SELECT @SQLSTR=@SQLSTR+'  (  '
		SELECT @SQLSTR=@SQLSTR+'select CLIENTID,sum(INAMOUNT) as INAMOUNT     '
		SELECT @SQLSTR=@SQLSTR+' from CLIENTBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+ @Now_Date +char(39) +' AND INOUTFLAG =-1 '  
		SELECT @SQLSTR=@SQLSTR+' group by CLIENTID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BN00 on BN00.CLIENTID = I.CLIENTID  '
------------------------以上部分为取begin_date到Now_Date的库存
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select CLIENTID,sum(INAMOUNT) as INAMOUNT   '
		SELECT @SQLSTR=@SQLSTR+' from CLIENTBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+@End_Date+char(39)+' AND INOUTFLAG =1 '  
		SELECT @SQLSTR=@SQLSTR+' group by CLIENTID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE on BE.CLIENTID = I.CLIENTID  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select CLIENTID,sum(INAMOUNT) as INAMOUNT   '
		SELECT @SQLSTR=@SQLSTR+' from CLIENTBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+@End_Date +char(39)+'AND INOUTFLAG =-1' 
		SELECT @SQLSTR=@SQLSTR+' group by CLIENTID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE00 on BE00.CLIENTID = I.CLIENTID  '
                          SELECT @SQLSTR=@SQLSTR+'  where     I. CLIENTID in (select CLIENTID from CLIENTBILLFLOW where YYYYMM>='+char(39)+@YYYYMM+char(39)+')'  + @WHERESTING 
	             SELECT @SQLSTR=@SQLSTR+'          order by  I.CLIENTID                '    
------------------------------------------------------------------------
--		       print   @SQLSTR

---		EXEC(@SQLSTR)

	INSERT INTO   #CLIENTTMP    EXEC(@SQLSTR)
	delete  #CLIENTTMP where  EAMOUNT=0



	    declare Cursor_BJ Cursor READ_ONLY for Select CLIENTID  from  #CLIENTTMP  ORDER BY CLIENTID

	    Open Cursor_BJ

	    fetch Cursor_BJ into @CLIENTID


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin


                   ---select @MAXBILLDATE=MAX(BILLDATE) FROM CLIENTbillflow   WHERE  CLIENTID=@CLIENTID
		    select @LastSKDate=max(billdate) from CLIENTBILLFLOW   WHERE  CLIENTID = @CLIENTID and BILLTYPE=4 and YYYYMMBILL=1
		    IF  @LastSKDate IS NULL
		    begin
			set @LastSKDate='2000-10-10'
		    end
	            update   #CLIENTTMP  SET LastSKDate=@LastSKDate WHERE  CLIENTID = @CLIENTID


	    fetch Cursor_BJ into @CLIENTID
 

	    END           ------- Cursor_BJ  WHILE

	    close Cursor_BJ
	    deallocate Cursor_BJ

             SELECT *  FROM #CLIENTTMP   WHERE   EAMOUNT > CREDIT  and (DATEDIFF(day, LastSKDate, getdate())>QiXianDays)



SET QUOTED_IDENTIFIER OFF 
SET ANSI_NULLS ON 

SET QUOTED_IDENTIFIER ON 
SET ANSI_NULLS OFF







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG
















CREATE PROCEDURE [CLIENT_CACULATOR_YYYYMM ]  (
	@CLIENTID  varchar(30),
	@YYYYMM  varchar(6)    )
AS 
 
declare @INOUTFLAG NUMERIC(20,10)
declare @INAMOUNT  NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @SUMBAMOUNT NUMERIC(20,10)            ---本期期初总金额
 
BEGIN

            select    @SUMBAMOUNT=isnull(BAMOUNT,0)   FROM   CLIENTBILLFlow  where    (rtrim(CLIENTID) = @CLIENTID) 
						  and (rtrim(YYYYMM) = @YYYYMM) 	and   ( YYYYMMBILL=0   )  
                                       -------以上是期初数据
----------------------------------------------------------------
	    declare CLIENT_CACULATOR Cursor for Select  CLIENTID , isnull(INAMOUNT,0) as INAMOUNT, INOUTFLAG, isnull(EAMOUNT,0) as EAMOUNT 
	                  from CLIENTBILLFlow   where (rtrim(YYYYMM) >= @YYYYMM)  AND ( CLIENTID=@CLIENTID)   and   ( YYYYMMBILL=1   )  
             		      ORDER BY BILLDATE,ID

	    Open CLIENT_CACULATOR

	    fetch CLIENT_CACULATOR into @CLIENTID,@INAMOUNT,@INOUTFLAG,@EAMOUNT


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
		 select    @SUMBAMOUNT=@SUMBAMOUNT+@INAMOUNT*@INOUTFLAG

	         	 UPDATE   CLIENTBILLFLOW  set   EAMOUNT=@SUMBAMOUNT      WHERE CURRENT OF  CLIENT_CACULATOR

		    fetch CLIENT_CACULATOR into @CLIENTID,@INAMOUNT,@INOUTFLAG,@EAMOUNT
 
	    END           ------- CLIENT_CACULATOR  WHILE

	    close CLIENT_CACULATOR
	    deallocate CLIENT_CACULATOR

-----------------------------------------------------------------------------------------------------------------------------------------------------------


END










----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG




















CREATE PROCEDURE [CREAT_QGD]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---是否现款标志
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @VENDORID   varchar(15)               --明细存货编号
declare @Cheng_GoodsName   varchar(50)               --明细存货编号
declare @Cheng_SpecName   varchar(50)               --明细存货编号
declare @bankID   varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @Cai_STOREID varchar(15)               --明细存货编号
declare @GoodsName varchar(50)               --明细存货编号
declare @QieSpecName varchar(50)               --明细存货编号
declare @QieChangDu NUMERIC(20,6)                          --数量
declare @QieKuanDu NUMERIC(20,6)                          --数量
declare @Cai_QieChangDu NUMERIC(20,6)                          --数量
declare @Cai_QieKuanDu NUMERIC(20,6)                          --数量
declare @RATE NUMERIC(20,10)                          --单据总金额
declare @goodsid varchar(15)               --明细存货编号
declare @Cai_GoodsID varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @SUMAMT NUMERIC(20,10)                          --单据总金额
declare @UNITQTY NUMERIC(20,10)                          --单据总金额
declare @StoreQTY NUMERIC(20,10)                          --单据总金额
declare @refqty NUMERIC(20,10)                          --引用数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @ChangCaiFLAG  INTEGER
declare @MeiQty  INTEGER
declare @KeJiaGongQty  INTEGER
declare @PRICETYPE INTEGER
declare @STOREHSFS   INTEGER  --分仓核算

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

set @BILLID   = ltrim(rtrim(@BILLID))

     set @BillDate =   (select BillDate  from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     



if  (select isnull(flagPost,0) from STOREQGDM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_QGD   --事物开始

     set @INOUTFLAG =   (select INOUTFLAG from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @VENDORID =   (select  VENDORID  from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @BANKID =   (select BANKID  from STOREQGDM where rtrim(BILLID) = @BILLID)   ---------付款银行




		delete STOREQGDS  where rtrim(BILLID) = @BILLID

    declare SM_Consign_QGD Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(unitPRICE,0) as PRICE, 
                                                                  DetailBillFlowID,UNITQTY    from STOREQGDD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_QGD

    fetch SM_Consign_QGD into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE, @DetailBillFlowID,@UNITQTY 

    while @@fetch_status = 0            ----开始
    begin



	    select @INF_COSTINGTYPEID=INF_COSTINGTYPEID,@RATE=ISNULL(RATE,0)*0.001,@QieSpecName=ISNULL(QieSpecName,''),
				@QieChangDu=ISNULL(QieChangDu,0),@QieKuanDu=ISNULL(QieKuanDu,0),
				@GoodsName=Name, @ChangCaiFLAG=ISNULL(ChangCaiFLAG,0),@Cheng_SpecName=SpecName
				from GOODS where  GOODSID = @GOODSID
	--------以上为成品参数 ，材料参数采用CaiLiao开头的变量

			set @Cheng_GoodsName=@GoodsName
-----分两步完成，第一步先把相匹配的材料选出，提取库存，第二部、利用递减法生成有效的记录


		    declare SM_Consign_QGD_00 Cursor for Select  GOODSID,QieChangDu,QieKuanDu   from Goods where @GoodsName=Name and @ChangCaiFLAG=ISNULL(ChangCaiFLAG,0) and @QieSpecName=ISNULL(QieSpecName,'')

		    Open SM_Consign_QGD_00

		    fetch SM_Consign_QGD_00 into @Cai_GoodsID,@Cai_QieChangDu,@Cai_QieKuanDu

		    while @@fetch_status = 0            ----开始
		    begin


----------------每个材料切割成品个数  
				select  @MeiQty=FLOOR(@Cai_QieChangDu/@QieChangDu)

				if @ChangCaiFLAG=0
				begin
				select  @MeiQty=FLOOR(@Cai_QieChangDu/@QieChangDu)*FLOOR(@Cai_QieKuanDu/@QieKuanDu)
				end
---				print @MeiQty

			    declare SM_Consign_QGD_11 Cursor for Select  distinct StoreID   from DetailBillFlow  where GoodsID=@Cai_GoodsID

			    Open SM_Consign_QGD_11
	
			    fetch SM_Consign_QGD_11 into @Cai_StoreID

			    while @@fetch_status = 0            ----开始
			    begin


                            	 EXEC   GETGOODSIDMEQTY  @Cai_StoreID,@Cai_GoodsID,@YYYYMM,@MEQTY=@StoreQTY   OUTPUT

				     set  @KeJiaGongQty=@StoreQTY*@MeiQty

				IF  @StoreQTY>0  and @MeiQty>0
				Begin
		                 execute  GETKEYVALUE     'STOREQGDS',@R_KeyValue = @NEWID output
				    insert into STOREQGDS 
				    (BILLID,ITEMNO,GOODSID,StoreID,StoreQTY,KeJiaGongQty,MeiQty,REITEMNO,Cheng_GoodsID,Cheng_UnitQTY,
					UNITQTY,
					Cheng_GoodsName,Cheng_SpecName)
				    Values
				    (@BillID,@NEWID,@Cai_GoodsID,@Cai_StoreID,@StoreQTY,@KeJiaGongQty,@MeiQty,@ITEMNO,@GoodsID,@UnitQTY,
					FLOOR(@UnitQTY/@MeiQty)+1,
					@Cheng_GoodsName,@Cheng_SpecName)
				end
			
				    fetch SM_Consign_QGD_11 into @Cai_StoreID
	
			    END           ------- SM_Consign_QGD_00  WHILE

			    close SM_Consign_QGD_11
			    deallocate SM_Consign_QGD_11



		    fetch SM_Consign_QGD_00 into @Cai_GoodsID,@Cai_QieChangDu,@Cai_QieKuanDu

		    END           ------- SM_Consign_QGD_00  WHILE

		    close SM_Consign_QGD_00
		    deallocate SM_Consign_QGD_00

	update STOREQGDS   set unitqty=StoreQTY     where rtrim(BILLID) = @BILLID  and MeiQty=1  and cheng_UnitQty>=StoreQTY



--------------------
    fetch SM_Consign_QGD into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE, @DetailBillFlowID,@UNITQTY 

    END           ------- SM_Consign_QGD  WHILE

    close SM_Consign_QGD
    deallocate SM_Consign_QGD

    

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_QGD
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_QGD
      set @flagreturn = 0
   end
end
















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG









--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------

CREATE PROCEDURE [CREAT_STRING_BILLNAME]                         --APSOFTENCRYPTION       WITH ENCRYPTION 
 AS                 


declare @BILLTYPEID varchar(30)                   --会计年月     
declare @NAME varchar(30)                   --单句会计年月     
declare @BILLFLAG varchar(15)               --明细存货编号    
declare @CCSTRING     Nvarchar(250)                   --会计年月     


Create Table #temptable10000
      (
   CCSTRING  nvarchar(250)  NULL
		)



    declare SM_Consign_XSCK_DEL Cursor for Select BILLTYPEID,NAME,BILLFLAG   from BILLNAME

    Open SM_Consign_XSCK_DEL

    fetch SM_Consign_XSCK_DEL into @BILLTYPEID,@NAME,@BILLFLAG 

    while @@fetch_status = 0            ----开始
    begin
                 SET @CCSTRING= '  INSERT  BILLNAME  (BILLTYPEID,NAME,BILLFLAG) '
                  SET @CCSTRING=@CCSTRING+'   Values  ( '+CHAR(39)+@BILLTYPEID+CHAR(39)+','+CHAR(39)+@NAME+CHAR(39)+','+CHAR(39)+@BILLFLAG+CHAR(39)+')'
                 INSERT  #temptable10000     Values  (@CCSTRING)
--------------------
      fetch SM_Consign_XSCK_DEL into @BILLTYPEID,@NAME,@BILLFLAG 

    END           ------- SM_Consign_XSCK_DEL  WHILE

    close SM_Consign_XSCK_DEL
    deallocate SM_Consign_XSCK_DEL
     
  SELECT * FROM  #temptable10000  WHERE   CCSTRING  IS  NOT NULL
   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG






















--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------

CREATE PROCEDURE [CREAT_STRING_BillSeeAbout]                         --APSOFTENCRYPTION       WITH ENCRYPTION 

 AS                 


declare @BillSeeAboutID varchar(6)                  
declare @PageControl varchar(6)                     
declare @STR varchar(15)               
declare @SunXu varchar(8)
declare @STORECGRKM varchar(8)                     
declare @STORECGTHM    varchar(15)
declare @STOREGJRKM varchar(8)              
declare @STORECGFKM   varchar(30)                     
declare @STOREXSCKM    Nvarchar(10)                   
declare @STOREXSTHM   Nvarchar(30)                 
declare @STOREXSSKM    Nvarchar(10) 
declare @STOREQTRKM    Nvarchar(10)
declare @STOREQTCKM    Nvarchar(10)
declare @STORECKDBM    Nvarchar(10)
declare @STORECKPDM    Nvarchar(10)
declare @STOREQTSRM    Nvarchar(10)
declare @STOREFYKZM    Nvarchar(10)
declare @STOREMOVEM    Nvarchar(10)
declare @STORECSHM   Nvarchar(10)                           
declare @STOREYunFeiFKM   Nvarchar(10)                           
declare @STOREXSDDM   Nvarchar(10)                           
declare @STORECGFPM   Nvarchar(10)                           
declare @STOREXSFPM   Nvarchar(10)                           
declare @STOREJGDM   Nvarchar(10)                           
declare @STOREQGDM   Nvarchar(10)                           
declare @STOREQGADM   Nvarchar(10)                           
declare @STORECGDDM   Nvarchar(10)                           
declare @CCSTRING11   Nvarchar(250)   
declare @CCSTRING22   Nvarchar(250)   
declare @CCSTRING33   Nvarchar(250)   


Create Table #temptable10000
      (
  CCSTRING  nvarchar(250)  NULL
		)



    declare SM_Consign_XSCK_DEL Cursor for Select BillSeeAboutID,PageControl,STR,SunXu,STORECGRKM,STORECGTHM,STOREGJRKM,STORECGFKM,STOREXSCKM,STOREXSTHM,STOREXSSKM,STOREQTRKM,STOREQTCKM,STORECKDBM,STORECKPDM,STOREQTSRM,STOREFYKZM,STOREMOVEM,STORECSHM,STOREYunFeiFKM,STOREXSDDM,STORECGFPM,STOREXSFPM,STOREQGADM,STORECGDDM,STOREJGDM,STOREQGDM   from BillSeeAbout

    Open SM_Consign_XSCK_DEL

    fetch SM_Consign_XSCK_DEL into @BillSeeAboutID,@PageControl,@STR,@SunXu,@STORECGRKM,@STORECGTHM,@STOREGJRKM,@STORECGFKM,@STOREXSCKM,@STOREXSTHM,@STOREXSSKM,@STOREQTRKM,@STOREQTCKM,@STORECKDBM,@STORECKPDM,@STOREQTSRM,@STOREFYKZM,@STOREMOVEM,@STORECSHM,@STOREYunFeiFKM,@STOREXSDDM,@STORECGFPM,@STOREXSFPM,@STOREQGADM,@STORECGDDM,@STOREJGDM,@STOREQGDM

    while @@fetch_status = 0            ----开始
    begin
                 SET @CCSTRING11= '  INSERT  BillSeeAbout (PageControl,STR,SunXu,STORECGRKM,STORECGTHM,STOREGJRKM,STORECGFKM,STOREXSCKM,STOREXSTHM,STOREXSSKM,STOREQTRKM, '
                 INSERT  #temptable10000     Values  (@CCSTRING11)
                 SET @CCSTRING22= '    STOREQTCKM,STORECKDBM,STORECKPDM,STOREQTSRM,STOREFYKZM,STOREMOVEM,STORECSHM,STOREYunFeiFKM,STOREXSDDM,STORECGFPM,STOREXSFPM,STOREQGADM,STORECGDDM,STOREJGDM,STOREQGDM) '
                 INSERT  #temptable10000     Values  (@CCSTRING22)
                  SET @CCSTRING33='   Values ( '+CHAR(39)+@PageControl+CHAR(39)+','+CHAR(39)+@STR+CHAR(39)+','+CHAR(39)+@SunXu+CHAR(39)+','+CHAR(39)+@STORECGRKM+CHAR(39)+','+CHAR(39)+@STORECGTHM+CHAR(39)+','+CHAR(39)+@STOREGJRKM+CHAR(39)+','+CHAR(39)+@STORECGFKM+CHAR(39)+','+CHAR(39)+@STOREXSCKM+CHAR(39)+','+CHAR(39)+@STOREXSTHM+CHAR(39)+','+CHAR(39)+@STOREXSSKM+CHAR(39)+','+CHAR(39)+@STOREQTRKM+CHAR(39)+','+CHAR(39)+@STOREQTCKM+CHAR(39)+','+CHAR(39)+@STORECKDBM+CHAR(39)+','+CHAR(39)+@STORECKPDM+CHAR(39)+','+CHAR(39)+@STOREQTSRM+CHAR(39)+','+CHAR(39)+@STOREFYKZM+CHAR(39)+','+CHAR(39)+@STOREMOVEM+CHAR(39)+','+CHAR(39)+@STORECSHM+CHAR(39)+','+CHAR(39)+@STOREYunFeiFKM+CHAR(39)+','+CHAR(39)+@STOREXSDDM+CHAR(39)+','+CHAR(39)+@STORECGFPM+CHAR(39)+','+CHAR(39)+@STOREXSFPM+CHAR(39)+','+CHAR(39)+@STOREQGADM+CHAR(39)+','+CHAR(39)+@STORECGDDM+CHAR(39)+','+CHAR(39)+@STOREJGDM+CHAR(39)+','+CHAR(39)+@STOREQGDM+CHAR(39)+')'
                 INSERT  #temptable10000     Values  (@CCSTRING33)
--------------------
    fetch SM_Consign_XSCK_DEL into @BillSeeAboutID,@PageControl,@STR,@SunXu,@STORECGRKM,@STORECGTHM,@STOREGJRKM,@STORECGFKM,@STOREXSCKM,@STOREXSTHM,@STOREXSSKM,@STOREQTRKM,@STOREQTCKM,@STORECKDBM,@STORECKPDM,@STOREQTSRM,@STOREFYKZM,@STOREMOVEM,@STORECSHM,@STOREYunFeiFKM,@STOREXSDDM,@STORECGFPM,@STOREXSFPM,@STOREQGADM,@STORECGDDM,@STOREJGDM,@STOREQGDM

    END           ------- SM_Consign_XSCK_DEL  WHILE

    close SM_Consign_XSCK_DEL
    deallocate SM_Consign_XSCK_DEL
     
  SELECT * FROM  #temptable10000  WHERE   CCSTRING  IS  NOT NULL
   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------












----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------

CREATE PROCEDURE [CREAT_STRING_FunctionM]                         --APSOFTENCRYPTION       WITH ENCRYPTION 
 AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @REDetailBillFlowID   varchar(30)                     --序列号
declare @Function_Id    Nvarchar(10)                   --会计年月     
declare @Function_Desc   Nvarchar(30)                   --会计年月     
declare @Program_Name    Nvarchar(10)                   --会计年月     
declare @Parent_Function_Id   Nvarchar(10)                   --会计年月     
declare @Control_Owner   Nvarchar(30)                   --会计年月     
declare @Control_Name    Nvarchar(30)                   --会计年月     
declare @Control_Type   Nvarchar(30)                   --会计年月     
declare @CCSTRING     Nvarchar(250)                   --会计年月     


Create Table #temptable10000
      (
   CCSTRING  nvarchar(250)  NULL
		)



    declare SM_Consign_XSCK_DEL Cursor for Select Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type   from FunctionM

    Open SM_Consign_XSCK_DEL

    fetch SM_Consign_XSCK_DEL into @Function_Id,@Parent_Function_Id,@Program_Name,@Function_Desc,@Control_Owner,@Control_Name,@Control_Type 

    while @@fetch_status = 0            ----开始
    begin
                 SET @CCSTRING= '  INSERT  FunctionM  (Function_Id,Parent_Function_Id,Program_Name,Function_Desc,Control_Owner,Control_Name,Control_Type) '
                  SET @CCSTRING=@CCSTRING+'   Values  ( '+CHAR(39)+@Function_Id+CHAR(39)+','+CHAR(39)+@Parent_Function_Id+CHAR(39)+','+CHAR(39)+@Program_Name+CHAR(39)+','+CHAR(39)+@Function_Desc+CHAR(39)+','+CHAR(39)+@Control_Owner+CHAR(39)+','+CHAR(39)+@Control_Name+CHAR(39)+','+CHAR(39)+@Control_Type+CHAR(39)+')'
                 INSERT  #temptable10000     Values  (@CCSTRING)
--------------------
      fetch SM_Consign_XSCK_DEL into  @Function_Id,@Parent_Function_Id,@Program_Name,@Function_Desc,@Control_Owner,@Control_Name,@Control_Type 

    END           ------- SM_Consign_XSCK_DEL  WHILE

    close SM_Consign_XSCK_DEL
    deallocate SM_Consign_XSCK_DEL
     
  SELECT * FROM  #temptable10000  WHERE   CCSTRING  IS  NOT NULL
   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------

CREATE PROCEDURE [CREAT_STRING_SETCOL]                         --APSOFTENCRYPTION       WITH ENCRYPTION 

 AS                 


declare @FEILDNAME varchar(30)                  
declare @lEN varchar(30)                     
declare @CHINESENAME varchar(30)               
declare @FABC varchar(10)
declare @FGROUP varchar(30)
declare @ProgramName varchar(20)                     
declare @BILLNAME    varchar(30)
declare @HAVEGROUP varchar(20)              
declare @SHOWFLAG   varchar(30)                     
declare @ID   varchar(30)                     
declare @QSLEN    Nvarchar(10)                   
declare @QSCHINESENAME   Nvarchar(30)                 
declare @QSSHOWFLAG    Nvarchar(10)                               
declare @CCSTRING   Nvarchar(250)   


Create Table #temptable10000
      (
  CCSTRING  nvarchar(250)  NULL
		)



    declare SM_Consign_XSCK_DEL Cursor for Select FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG   from SETCOL

    Open SM_Consign_XSCK_DEL

    fetch SM_Consign_XSCK_DEL into @FEILDNAME,@lEN,@CHINESENAME,@FABC,@FGROUP,@ProgramName,@BILLNAME,@HAVEGROUP,@SHOWFLAG,@ID,@QSLEN,@QSCHINESENAME,@QSSHOWFLAG

    while @@fetch_status = 0            ----开始
    begin
	IF @FGROUP IS NULL
	BEGIN
                 SET @CCSTRING= '  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG) '
                  SET @CCSTRING=@CCSTRING+'   Values  ( '+CHAR(39)+@FEILDNAME+CHAR(39)+', '+CHAR(39)+@lEN+CHAR(39)+','+CHAR(39)+@CHINESENAME+CHAR(39)+','+CHAR(39)+@FABC+CHAR(39)+','+CHAR(39)+@ProgramName+CHAR(39)+','+CHAR(39)+@BILLNAME+CHAR(39)+','+@HAVEGROUP+','+CHAR(39)+@SHOWFLAG+CHAR(39)+','+CHAR(39)+@ID+CHAR(39)+','+CHAR(39)+@QSLEN+CHAR(39)+','+CHAR(39)+@QSCHINESENAME+CHAR(39)+','+CHAR(39)+@QSSHOWFLAG+CHAR(39)+')'
	END
	ELSE
	BEGIN
                  SET @CCSTRING= '  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG) '
                  SET @CCSTRING=@CCSTRING+'   Values  ( '+CHAR(39)+@FEILDNAME+CHAR(39)+', '+CHAR(39)+@lEN+CHAR(39)+','+CHAR(39)+@CHINESENAME+CHAR(39)+','+CHAR(39)+@FABC+CHAR(39)+','+CHAR(39)+@FGROUP+CHAR(39)+','+CHAR(39)+@ProgramName+CHAR(39)+','+CHAR(39)+@BILLNAME+CHAR(39)+','+CHAR(39)+@HAVEGROUP+CHAR(39)+','+CHAR(39)+@SHOWFLAG+CHAR(39)+','+CHAR(39)+@ID+CHAR(39)+','+CHAR(39)+@QSLEN+CHAR(39)+','+CHAR(39)+@QSCHINESENAME+CHAR(39)+','+CHAR(39)+@QSSHOWFLAG+CHAR(39)+')'
	END
                 INSERT  #temptable10000     Values  (@CCSTRING)
--------------------
      fetch SM_Consign_XSCK_DEL into @FEILDNAME,@lEN,@CHINESENAME,@FABC,@FGROUP,@ProgramName,@BILLNAME,@HAVEGROUP,@SHOWFLAG,@ID,@QSLEN,@QSCHINESENAME,@QSSHOWFLAG

    END           ------- SM_Consign_XSCK_DEL  WHILE

    close SM_Consign_XSCK_DEL
    deallocate SM_Consign_XSCK_DEL
     
  SELECT * FROM  #temptable10000  WHERE   CCSTRING  IS  NOT NULL
   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------

CREATE PROCEDURE [CREAT_STRING_Sys_DictTable]                         --APSOFTENCRYPTION       WITH ENCRYPTION 

 AS                 


declare @TableName varchar(20)                  
declare @FieldName varchar(20)                     
declare @FieldType varchar(15)               
declare @ChineseName varchar(20)                     
declare @ChineseTableName    varchar(30)              
declare @SystemName   varchar(30)                     
declare @FieldOrder   varchar(30)                     
declare @Remark    Nvarchar(10)                   
declare @FieldSize   Nvarchar(30)                 
declare @ExeclIn    Nvarchar(10)                          
declare @EXECLINMUST   Nvarchar(10)                          
declare @CCSTRING11   Nvarchar(250)   
declare @CCSTRING22   Nvarchar(250)   


Create Table #temptable10000
      (
  CCSTRING  nvarchar(250)  NULL
		)



    declare SM_Consign_XSCK_DEL Cursor for Select TableName,FieldName,FieldType,ChineseName,ChineseTableName,SystemName,FieldOrder,Remark,FieldSize,ExeclIn,EXECLINMUST   from Sys_DictTable  where TableName in ('GOODS','VENDOR','CLIENT')  AND EXECLIN=1

    Open SM_Consign_XSCK_DEL

    fetch SM_Consign_XSCK_DEL into @TableName,@FieldName,@FieldType,@ChineseName,@ChineseTableName,@SystemName,@FieldOrder,@Remark,@FieldSize,@ExeclIn,@EXECLINMUST

    while @@fetch_status = 0            ----开始
    begin
                 SET @CCSTRING11= '  INSERT  Sys_DictTable  (TableName,FieldName,FieldType,ChineseName,ChineseTableName,SystemName,FieldOrder,Remark,FieldSize,ExeclIn,EXECLINMUST) '
                 INSERT  #temptable10000     Values  (@CCSTRING11)
                  SET @CCSTRING22='   Values  ( '+CHAR(39)+@TableName+CHAR(39)+', '+CHAR(39)+@FieldName+CHAR(39)+','+CHAR(39)+@FieldType+CHAR(39)+','+CHAR(39)+@ChineseName+CHAR(39)+','+CHAR(39)+@ChineseTableName+CHAR(39)+','+CHAR(39)+@SystemName+CHAR(39)+','+CHAR(39)+@FieldOrder+CHAR(39)+','+CHAR(39)+@Remark+CHAR(39)+','+CHAR(39)+@FieldSize+CHAR(39)+','+CHAR(39)+@ExeclIn+CHAR(39)+','+CHAR(39)+@EXECLINMUST+CHAR(39)+')'
                 INSERT  #temptable10000     Values  (@CCSTRING22)
--------------------
    fetch SM_Consign_XSCK_DEL into @TableName,@FieldName,@FieldType,@ChineseName,@ChineseTableName,@SystemName,@FieldOrder,@Remark,@FieldSize,@ExeclIn,@EXECLINMUST

    END           ------- SM_Consign_XSCK_DEL  WHILE

    close SM_Consign_XSCK_DEL
    deallocate SM_Consign_XSCK_DEL
     
  SELECT * FROM  #temptable10000  WHERE   CCSTRING  IS  NOT NULL
--  SELECT * FROM  #temptable10000  
   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG



















--------------------------------------------------------------------

CREATE PROCEDURE CW_BETWEEN_CURR_YYYYMM  
                 (
                  @BILLDATE DATEtime,
                  @flagreturn int output,     ---返回记帐成功  -- 0 不在此会计期间  --1 在会计期间
                  @BillYYYYMMreturn VARCHAR(10) output     ---返回记帐成功  -- 0 不在此会计期间  --1 在会计期间
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     

declare @MINBILLDATE DATEtime
declare @MAXBILLDATE DATEtime
declare @PRODUCTDATE DATEtime
declare @Next_YYYYMMDate DATEtime
declare @B_ID INTEGER
declare @STOREHSFS   INTEGER

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

     select @flagreturn = 1     

   declare  @PREV_YYYYMM          varchar(6)  -- 上一个会计年月
   declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='CW_YYYYMM')  

   
	if substring(@YYYYMM,5,2) = '12'  --- 如果当前会计月等于最大的会计月，将需要转入下年的的第一个会计年月
	begin
	    set @Next_YYYYMM   = convert(varchar,convert(int,substring(@YYYYMM,1,4))+1) +'01'  
	end
	else
	begin
	    set @Next_YYYYMM   = substring(@YYYYMM,1,4) +substring('00',1,2-len(convert(varchar,convert(int,substring(@YYYYMM,5,2))+1)))+convert(varchar,convert(int,substring(@YYYYMM,5,2))+1)
	end

	if substring(@YYYYMM,5,2) = '01'  --- 如果当前会计月等于最大的会计月，将需要转入下年的的第一个会计年月
	begin
	    set @PREV_YYYYMM   = convert(varchar,convert(int,substring(@YYYYMM,1,4))-1) +'12'  
	end
	else
	begin
	    set @PREV_YYYYMM   = substring(@YYYYMM,1,4) +substring('00',1,2-len(convert(varchar,convert(int,substring(@YYYYMM,5,2))-1)))+convert(varchar,convert(int,substring(@YYYYMM,5,2))-1)
	end

	declare @YYYYMMFS INTEGER
	declare @YYYYMMFSDATE  INTEGER
	declare @Billday  INTEGER

	       SELECT    @YYYYMMFS =(SELECT  YYYYMMFS   FROM   ACCINFO    WHERE   GUID='0001' )    
                IF @YYYYMMFS=1
	  BEGIN
		     SET  @MINBillDate = CONVERT(DATEtime,@YYYYMM+'01')
		     SET  @MAXBillDate =CONVERT(DATEtime,@Next_YYYYMM+'01')
		     set @BillYYYYMMreturn=convert(varchar,DATEPART(year,@BillDate))+substring('00',1,2-len(convert(varchar,DATEPART(month,@BillDate))))+convert(varchar,DATEPART(month,@BillDate))
	  END
               ELSE
               BEGIN
	       SELECT    @YYYYMMFSDATE =(SELECT  YYYYMMFSDATE   FROM   ACCINFO    WHERE   GUID='0001' )    
       
	     SET  @MINBillDate =DATEADD(day, @YYYYMMFSDATE, CONVERT(DATEtime,@PREV_YYYYMM+'01'))
	     SET  @MAXBillDate =DATEADD(day, @YYYYMMFSDATE, CONVERT(DATEtime,@YYYYMM+'01'))
        	SELECT @Billday =DATEPART(day, @BillDate)
		if @Billday> @YYYYMMFSDATE  -----分界线
		begin
		     set @BillYYYYMMreturn=convert(varchar,DATEPART(year,DATEADD(month,1,@BillDate)))+substring('00',1,2-len(convert(varchar,DATEPART(month,DATEADD(month,1,@BillDate)))))+convert(varchar,DATEPART(month,DATEADD(month,1,@BillDate)))
		end
		else
		begin
		     set @BillYYYYMMreturn=convert(varchar,DATEPART(year,@BillDate))+substring('00',1,2-len(convert(varchar,DATEPART(month,@BillDate))))+convert(varchar,DATEPART(month,@BillDate))
		end



	 END

----      IF (@BillDate<@MINBillDate)  OR (@BillDate>=@MAXBillDate)
----可以记账当前会计期间以后的单据
      IF (@BillDate<@MINBillDate)  
      BEGIN
      set @flagreturn = 0
      RETURN
      END










----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG
















CREATE PROCEDURE [dbo].[CW_BILL_XuHao_ChongPai](
                  @TableName varchar(50),      ---单据编号   
                  @BILLID varchar(22)      ---单据编号   

)  
AS 
 
declare @YYYYMM  varchar(10)
declare @ITEMNO  varchar(10)
declare @INAMOUNT  NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @SUMBAMOUNT NUMERIC(20,10)            ---本期期初总金额
declare     @RETURNSTRINGXX    varchar(60)   
declare     @XuHao int 
 
BEGIN


----exec CW_BILL_XuHao_ChongPai 'STORECW_LRBMBD' ,'00000007'

    IF @TableName='STORECW_LRBMBD'
    begin

	    set @XuHao=1	
	    declare CW_BILL_XuHao_ChongPai_Cursor Cursor for Select ItemNO from STORECW_LRBMBD   where BILLID = @BILLID
            		      ORDER BY ItemNO

	    Open CW_BILL_XuHao_ChongPai_Cursor

	    fetch CW_BILL_XuHao_ChongPai_Cursor into @ItemNO


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin

		    update STORECW_LRBMBD set   xuhao=@xuhao   where ItemNO=@ItemNO
		    set @XuHao=@XuHao+1	

		    fetch CW_BILL_XuHao_ChongPai_Cursor into @ItemNO
 
	    END           ------- CW_BILL_XuHao_ChongPai_Cursor  WHILE

	    close CW_BILL_XuHao_ChongPai_Cursor
	    deallocate CW_BILL_XuHao_ChongPai_Cursor

    end

-----------------------------------------------------------------------------------------------------------------------------------------------------------
    IF @TableName='STORECW_ZCFZBMBD'
    begin

	    set @XuHao=1	
	    declare CW_BILL_XuHao_ChongPai_Cursor Cursor for Select ItemNO from STORECW_ZCFZBMBD   where BILLID = @BILLID
            		      ORDER BY ItemNO

	    Open CW_BILL_XuHao_ChongPai_Cursor

	    fetch CW_BILL_XuHao_ChongPai_Cursor into @ItemNO


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin

		    update STORECW_ZCFZBMBD set   xuhao=@xuhao   where ItemNO=@ItemNO
		    set @XuHao=@XuHao+1	

		    fetch CW_BILL_XuHao_ChongPai_Cursor into @ItemNO
 
	    END           ------- CW_BILL_XuHao_ChongPai_Cursor  WHILE

	    close CW_BILL_XuHao_ChongPai_Cursor
	    deallocate CW_BILL_XuHao_ChongPai_Cursor

    end

-----------------------------------------------------------------------------------------------------------------------------------------------------------
    IF @TableName='STORECW_XJLLBMBD'
    begin

	    set @XuHao=1	
	    declare CW_BILL_XuHao_ChongPai_Cursor Cursor for Select ItemNO from STORECW_XJLLBMBD   where BILLID = @BILLID
            		      ORDER BY ItemNO

	    Open CW_BILL_XuHao_ChongPai_Cursor

	    fetch CW_BILL_XuHao_ChongPai_Cursor into @ItemNO


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin

		    update STORECW_XJLLBMBD set   xuhao=@xuhao   where ItemNO=@ItemNO
		    set @XuHao=@XuHao+1	

		    fetch CW_BILL_XuHao_ChongPai_Cursor into @ItemNO
 
	    END           ------- CW_BILL_XuHao_ChongPai_Cursor  WHILE

	    close CW_BILL_XuHao_ChongPai_Cursor
	    deallocate CW_BILL_XuHao_ChongPai_Cursor

    end

-----------------------------------------------------------------------------------------------------------------------------------------------------------



END







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














--------------------------------------------------------------------插入月结记录

CREATE PROCEDURE [dbo].[CW_BillFlow_insert_YYYYMM]  
                 (	
	@ItemBM varchar(30)
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @VENDORFLAG int           ---单据类型
declare @NEWID varchar(15)               --明细存货编号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @B_CODE VARCHAR(25)
declare @B_ID INTEGER
declare @Detailflag int           ---单据类型
declare @BenYueLastDay  VARCHAR(10)

--------增加对新增的科目增加所有月结记录
---     set @YYYYMM   = (select optionvalue from accoptions where optionname ='CW_YYYYMM') 


     declare CW_BillFlow_YYYYMM Cursor for     Select  Distinct YYYYMM from CW_BillFlow  

	    Open CW_BillFlow_YYYYMM

	    fetch CW_BillFlow_YYYYMM into @YYYYMM 


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin



		     Select @BenYueLastDay =CONVERT(varchar(100), dateadd(dd,-1,dateadd(m,1,Substring(@YYYYMM,1,4)+'-'+Substring(@YYYYMM,5,2)+'-01')), 23)

      
		     select @Detailflag=Detailflag from ItemInfo where ItemBM=@ItemBM


	            IF not exists(select *  from CW_BILLFLOW  where 
             		                                    (rtrim(ItemBM) = @ItemBM)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 )       
	            BEGIN
                     execute  GETKEYVALUE     'CW_BillFlow',@R_KeyValue = @NEWID output
		    insert into CW_BillFlow 
		    (ID,YYYYMM,YYYYMMBILL,ItemBM,
		     BAMOUNT,debit,credit,EAMOUNT,Detailflag,brief,BILLDATE,XuHao)
		    Values
		    (@NEWID,@YYYYMM,0,@ItemBM,0,0,0,0,@Detailflag,'本期合计',@BenYueLastDay,'88888888')  
	            END      ------IF   END

------------------------------------------------------------------------------
	            IF not exists(select *  from CW_BILLFLOW  where 
             		                                    (rtrim(ItemBM) = @ItemBM)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 2)       ---2代表本期合计记录
             		                                 )       
	            BEGIN
                     execute  GETKEYVALUE     'CW_BillFlow',@R_KeyValue = @NEWID output
		    insert into CW_BillFlow 
		    (ID,YYYYMM,YYYYMMBILL,ItemBM,
		     BAMOUNT,debit,credit,EAMOUNT,Detailflag,brief,BILLDATE,XuHao)
		    Values
		    (@NEWID,@YYYYMM,2,@ItemBM,0,0,0,0,@Detailflag,'本年累计',@BenYueLastDay,'99999999')
	            END      ------IF   END

----------------------------------------------------------------------------------
/*	            IF not exists(select *  from CW_BILLFLOW  where 
             		                                    (rtrim(ItemBM) = @ItemBM)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 3)       ---3代表会计科目初始化本年累计记录
             		                                 )       
	            BEGIN
                     execute  GETKEYVALUE     'CW_BillFlow',@R_KeyValue = @NEWID output
		    insert into CW_BillFlow 
		    (ID,YYYYMM,YYYYMMBILL,ItemBM,
		     BAMOUNT,debit,credit,EAMOUNT,Detailflag)
		    Values
		    (@NEWID,@YYYYMM,3,@ItemBM,0,0,0,0,@Detailflag)    
	            END      ------IF   END

*/

		    fetch CW_BillFlow_YYYYMM into @YYYYMM
 
	    END           ------- CW_BillFlow_YYYYMM  WHILE

	    close CW_BillFlow_YYYYMM
	    deallocate CW_BillFlow_YYYYMM
		

SET QUOTED_IDENTIFIER OFF







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG
















CREATE PROCEDURE [dbo].[CW_CACULATOR_YYYYMM ]  (
	@ItemBM  varchar(30),
	@YYYYMM  varchar(6)    )
AS 
 
declare @Debit  NUMERIC(20,2)
declare @Credit NUMERIC(20,2)
declare @EAMOUNT NUMERIC(20,2)
declare @SUMBAMOUNT NUMERIC(20,2)            ---本期期初总金额
declare @JHD int

 
BEGIN


		select @JHD =JHD from ItemInfo where rtrim(ItemBM) = @ItemBM

            select    @SUMBAMOUNT=isnull(BAMOUNT,0)   FROM   CW_BILLFlow  where    (rtrim(ItemBM) = @ItemBM) 
						  and (rtrim(YYYYMM) = @YYYYMM) 	and   ( YYYYMMBILL=0   )  

                                       -------以上是期初数据
----------------------------------------------------------------
	    declare CW_CACULATOR Cursor for Select  ItemBM , isnull(Debit,0) as Debit, isnull(Credit,0) as Credit, isnull(EAMOUNT,0) as EAMOUNT 
	                  from CW_BILLFlow   where (rtrim(YYYYMM) >= @YYYYMM)  AND ( ItemBM=@ItemBM)   and   ( YYYYMMBILL=1   )  
             		      ORDER BY BILLDATE,ID

	    Open CW_CACULATOR

	    fetch CW_CACULATOR into @ItemBM,@Debit,@Credit,@EAMOUNT


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
		 select    @SUMBAMOUNT=@SUMBAMOUNT+(@Debit-@Credit)*@JHD
--		print @JHD
--		 select    @SUMBAMOUNT=@SUMBAMOUNT+@Debit-@Credit

	         	 UPDATE   CW_BILLFlow  set   EAMOUNT=@SUMBAMOUNT      WHERE CURRENT OF  CW_CACULATOR

		    fetch CW_CACULATOR into @ItemBM,@Debit,@Credit,@EAMOUNT
 
	    END           ------- CW_CACULATOR  WHILE

	    close CW_CACULATOR
	    deallocate CW_CACULATOR

-----------------------------------------------------------------------------------------------------------------------------------------------------------
-----------------------解决本期合计

			update CW_BILLFLOW   set  Debit=( select isnull(sum(Debit),0) from  CW_BILLFLOW
                                    where ItemBM = @ItemBM and(rtrim(YYYYMMBILL) = 1)  and (rtrim(YYYYMM) = @YYYYMM)  ) ,
						  Credit=( select isnull(sum(Credit),0) from  CW_BILLFLOW
                                    where ItemBM = @ItemBM and(rtrim(YYYYMMBILL) = 1) and (rtrim(YYYYMM) = @YYYYMM) )  					  						       
					        where    (rtrim(ItemBM) = @ItemBM)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)

			update CW_BILLFLOW   set  EAMOUNT=isnull(BAMOUNT,0)+(isnull(Debit,0)-isnull(Credit,0))*@JHD
					        where    (rtrim(ItemBM) = @ItemBM)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)
-------------------------------------------------------------------------------------------------
-----------------------解决本年累计

			update CW_BILLFLOW   set  Debit=( select isnull(sum(Debit),0) from  CW_BILLFLOW
                                    where ItemBM = @ItemBM and(rtrim(YYYYMMBILL) in (1,3)) ) ,
						  Credit=( select isnull(sum(Credit),0) from  CW_BILLFLOW
                                    where ItemBM = @ItemBM and(rtrim(YYYYMMBILL) in (1,3)) )  					  						       
					        where    (rtrim(ItemBM) = @ItemBM)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 2)



END












----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG








-------------2006.01.23  修改为不传递会计期间进行月末结帐

-------------------------------------------------------------------

CREATE PROCEDURE [dbo].[CW_DataToNext] (
                              @IsSuccess         int output     ---返回成功  -- 0 不成功  --1 
                            )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
Begin transaction CWDataToNext
declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月
declare  @SQLSTR         varchar(8000)  -- 下一个会计年月
declare         @Current_YYYYMM  varchar(20)   --传入当前会计期间


declare @YYYYMM varchar(6)                   --会计年月     

declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)

declare @YYYYMMBILL int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @CLIENTID varchar(15)               --明细存货
declare @VENDORID varchar(15)               --明细存货编号
declare @BANKID varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @Bqty NUMERIC(20,10)                          --数量
declare @BAMOUNT NUMERIC(20,10)                          --数量
declare @Eqty NUMERIC(20,10)                          --数量
declare @EAMOUNT NUMERIC(20,10)                          --数量



declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @B_ID INTEGER
declare @BenYueLastDay  VARCHAR(10)

     set  @Current_YYYYMM   = (select optionvalue from accoptions where optionname ='CW_YYYYMM') 
    

if substring(@Current_YYYYMM,5,2) = '12'  --- 如果当前会计月等于最大的会计月，将需要转入下年的的第一个会计年月
begin
    set @Next_YYYYMM   = convert(varchar,convert(int,substring(@Current_YYYYMM,1,4))+1) +'01'  
end
else
begin
    set @Next_YYYYMM   = substring(@Current_YYYYMM,1,4) +substring('00',1,2-len(convert(varchar,convert(int,substring(@Current_YYYYMM,5,2))+1)))+convert(varchar,convert(int,substring(@Current_YYYYMM,5,2))+1)
end


--------判断当前会计期间是否月结，不能重复月结

	  if exists(Select * from CW_PingZhengM where YYYYMM=@Current_YYYYMM AND ISNULL(FlagPost,0)=0)
	  begin
		   commit transaction CWDataToNext
		   set @IsSuccess=0

	  end

-------declare @flagreturn int 
-------exec STORE_YYYYMM_INSERT   @flagreturn output 
	Select @BenYueLastDay =CONVERT(varchar(100), dateadd(dd,-1,dateadd(m,1,Substring(@Next_YYYYMM,1,4)+'-'+Substring(@Next_YYYYMM,5,2)+'-01')), 23)


--------取得接转当前会计期间的数据并复制到临时表中 begin --------------------------------
	delete  CW_BILLFLOWTMP

        INSERT  INTO   CW_BILLFLOWTMP  Select * from  CW_BILLFLOW where yyyymmbill=0 and YYYYMM=@Current_YYYYMM

        update   CW_BILLFLOWTMP  set YYYYMM=@Next_YYYYMM ,BAMOUNT=EAMOUNT,Debit=0,Credit=0,ID=SubString(ID,1,8)+@Next_YYYYMM,BillDate=@BenYueLastDay

    	INSERT  INTO   CW_BILLFLOW  Select * from  CW_BILLFLOWTMP where yyyymmbill=0


-----------------------
	delete  CW_BILLFLOWTMP

        INSERT  INTO   CW_BILLFLOWTMP  Select * from  CW_BILLFLOW where yyyymmbill=2 and YYYYMM=@Current_YYYYMM

        update   CW_BILLFLOWTMP  set YYYYMM=@Next_YYYYMM ,ID=SubString(ID,1,8)+@Next_YYYYMM,BillDate=@BenYueLastDay

    	INSERT  INTO   CW_BILLFLOW  Select * from  CW_BILLFLOWTMP where yyyymmbill=2

--	delete CW_BILLFLOW where YYYYMM='201309' and yyyymmbill in (0,2)
--      update   accoptionS  set optionvalue='201308'           where optionname ='CW_YYYYMM' 
  update   accoptionS  set optionvalue=@Next_YYYYMM           where optionname ='CW_YYYYMM'
     





--------取得接转当前会计期间的数据并复制到临时表中 end ------------------------------------

--写结转信息
  If @@error = 0
  begin
     commit transaction CWDataToNext
   set @IsSuccess=1
  end
  else
  begin
    rollback transaction CWDataToNext
   set @IsSuccess=0
    raiserror('结转失败 ', 1, 20) 
  end








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG









-------------2006.01.23  修改为不传递会计期间进行取消月末结帐


CREATE PROCEDURE [dbo].[CW_DataToNextDel] (
			 @FlagDel    int ,     ----------删除结转损益产生的凭证
                              @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                              @IsSuccess         int output     ---返回成功  -- 0 不成功  --1 
                            )  --APSOFTENCRYPTION       WITH ENCRYPTION
 AS 
Begin transaction CWDataToNext

   declare  @PREV_YYYYMM          varchar(6)  -- 上一个会计年月
   declare  @Current_YYYYMM          varchar(6)  -- 上一个会计年月
   declare  @GOODSID          varchar(10)  -- 上一个会计年月
   declare  @STOREID         varchar(10)  -- 上一个会计年月
   declare  @CLIENTID         varchar(10)  -- 上一个会计年月
   declare  @VENDORID         varchar(10)  -- 上一个会计年月
   declare  @BANKID         varchar(10)  -- 上一个会计年月
   declare  @BILLID          varchar(10)  -- 上一个会计年月
   declare  @BEGINYYYYMM          varchar(10)  -- 上一个会计年月
declare @RETURNSTRINGXX    varchar(60)   
declare @flagreturnXX int 
declare @ItemBM varchar(20)               --明细存货编号
declare @NewItemBM varchar(20)               --明细存货编号
declare @PrevNO varchar(20)               --明细存货编号
declare @Detailflag   INT
declare @BenNianLRKeMu  varchar(30) 


      SET @RETURNSTRING='  '
     set  @Current_YYYYMM   = (select optionvalue from accoptions where optionname ='CW_YYYYMM')     
	if substring(@Current_YYYYMM,5,2) = '01'  --- 如果当前会计月等于最大的会计月，将需要转入下年的的第一个会计年月
	begin
	    set @PREV_YYYYMM   = convert(varchar,convert(int,substring(@Current_YYYYMM,1,4))-1) +'12'  
	end
	else
	begin
	    set @PREV_YYYYMM   = substring(@Current_YYYYMM,1,4) +substring('00',1,2-len(convert(varchar,convert(int,substring(@Current_YYYYMM,5,2))-1)))+convert(varchar,convert(int,substring(@Current_YYYYMM,5,2))-1)
	end

	IF  NOT (exists (SELECT * FROM CW_BILLFLOW  where YYYYMM=@PREV_YYYYMM)) 

	BEGIN
			      rollback transaction CWDataToNext
			      set @IsSuccess   = 0
                              SET @RETURNSTRING='启用帐套的会计期间不能反结账！'
                              RETURN
	END 

       	 DELETE  CW_BILLFLOW  where YYYYMM=@Current_YYYYMM   and  YYYYMMBILL IN ( 0,1,2)   

  
         update   accoptionS  set optionvalue=@PREV_YYYYMM        where optionname ='CW_YYYYMM'

-----@BenNianLRKeMu='3131'
	select @BenNianLRKeMu=BenNianLRKeMu  FROM  ACCINFO  WHERE GUID='0001'



        IF @FlagDel =1 
	begin

	

	 delete  CW_PingZhengM where BILLID IN (Select BILLID from CW_PingZhengD where ItemBM =@BenNianLRKeMu AND YYYYMM=@PREV_YYYYMM)

       	 DELETE  CW_BILLFLOW  where  YYYYMMBILL=1  and (BILLID NOT IN (Select BILLID from CW_PingZhengD))


		    declare Cursor_CW_DataToNextDel Cursor for Select Itembm from  Iteminfo  where DetailFlag=1 and (Itembm Like '5%' OR  ItemBM =@BenNianLRKeMu) 
								Order By Itembm
		    Open Cursor_CW_DataToNextDel

		    fetch Cursor_CW_DataToNextDel into @Itembm

		    while @@fetch_status = 0            ----开始
		    begin

			    set @NewItemBM=@ItemBM
			
			    select @PrevNO='9999AAAA'

		
			      while  (@PrevNO<>'0000') 
			      begin
			        select @Detailflag=Detailflag from ItemInfo where ItemBM=@NewItemBM

			      execute   CW_CACULATOR_YYYYMM @NewItemBM,@PREV_YYYYMM
	
			        select @PrevNO=PrevNO from ItemInfo where ItemBM=@NewItemBM


				SET @NewItemBM=@PrevNO
		
			     end          -------while  @PrevNO<>'0000' 



		    fetch Cursor_CW_DataToNextDel into @Itembm

		    END           ------- Cursor_CW_DataToNextDel  WHILE

		    close Cursor_CW_DataToNextDel
		    deallocate Cursor_CW_DataToNextDel




	end




------





--------取得接转当前会计期间的数据并复制到临时表中 end ------------------------------------

--写结转信息
  If @@error = 0
  begin
     commit transaction CWDataToNext
   set @IsSuccess=1
  end
  else
  begin
    rollback transaction CWDataToNext
   set @IsSuccess=0
    raiserror('结转失败 ', 1, 20) 
  end









----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG























--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[CW_Data_START] (
                              @START_YYYYMM   varchar(20),   --传入当前会计期间
                              @START_YYYYMMDD  DATETIME,   --传入当前时间
                              @IsSuccess         int output     ---返回成功  -- 0 不成功  --1 
                            )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
Begin transaction CW_Start
   declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月
   declare  @SQLSTR         varchar(8000)  -- 下一个会计年月


declare @YYYYMM varchar(6)                   --会计年月     
declare @Current_YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。


declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)

declare @bill_type int           ---单据类型
declare @Detailflag int           ---单据类型
declare @YYYYMMBILL int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @VENDORID varchar(15)               --明细存货编号
declare @ItemBM varchar(20)               --明细存货编号
declare @NewItemBM varchar(20)               --明细存货编号
declare @PrevNO varchar(20)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,2)                          --数量
declare @PRICE  NUMERIC(20,2)               --含税单价
declare @Bqty NUMERIC(20,2)                          --数量
declare @BAMOUNT NUMERIC(20,2)                          --数量
declare @SumBAMOUNT NUMERIC(20,2)                          --数量
declare @EAMOUNT NUMERIC(20,2)                          --数量
declare @SumEAMOUNT NUMERIC(20,2)                          --数量
declare @BEGINAMOUNT NUMERIC(20,2)                          --数量
declare @balance NUMERIC(20,2)                          --数量
declare @Debit NUMERIC(20,2)                          --数量
declare @Credit NUMERIC(20,2)                          --数量
declare @SumDebit NUMERIC(20,2)                          --数量
declare @SumCredit NUMERIC(20,2)                          --数量

declare @BATCHCODE varchar(30)                     --序列号
declare @VALIDDATE DATEtime



declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BANKID VARCHAR(25)
declare @BILLDATE DATEtime
declare @B_ID INTEGER
declare @CW_STATUS INTEGER
declare @BenYueLastDay  VARCHAR(10)
  


	        set @YYYYMM    = @START_YYYYMM
         	SET @CW_STATUS =(select   ISNULL(CW_STATUS,0)   FROM  ACCINFO  WHERE GUID='0001')
---            set @YYYYMM   = (select optionvalue from accoptions where optionname ='CW_YYYYMM')       

            IF  @CW_STATUS=1                      ----已经启用帐套
             BEGIN
	     commit transaction CW_Start  

	   	   set @IsSuccess=1
	             RETURN
             END

--判断当前会计期间是否月结，不能重复月结


------为已经做凭证做准备

------删除当前启用帐套会计期间的月结记录

     Select @BenYueLastDay =CONVERT(varchar(100), dateadd(dd,-1,dateadd(m,1,Substring(@YYYYMM,1,4)+'-'+Substring(@YYYYMM,5,2)+'-01')), 23)

--------------其实会计科目初始化里面全部为明细科目

    delete  CW_BILLFLOW where YYYYMM = @YYYYMM and (YYYYMMBILL in (0,2,3))

    declare Cur_CLIENT_100 Cursor for Select   ItemBM,ISNULL(Debit,0) as Debit, ISNULL(Credit,0) as Credit ,ISNULL(balance,0) as balance  from CW_initbala   order by  ItemBM

    Open Cur_CLIENT_100

    fetch Cur_CLIENT_100 into    @ItemBM,@Debit, @Credit,@balance
    while @@fetch_status = 0            ----开始
    begin


		    set @NewItemBM=@ItemBM
			
		    select @PrevNO='9999AAAA'

		
	      while  (@PrevNO<>'0000') 
	      begin
	        select @Detailflag=Detailflag from ItemInfo where ItemBM=@NewItemBM


	            IF not exists(select *  from CW_BILLFLOW  where 
             		                                    (rtrim(ItemBM) = @NewItemBM)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 )       
	            BEGIN
                     execute  GETKEYVALUE     'CW_BillFlow',@R_KeyValue = @NEWID output
		    insert into CW_BillFlow 
		    (ID,YYYYMM,YYYYMMBILL,ItemBM,
		     BAMOUNT,debit,credit,EAMOUNT,Detailflag,brief,BILLDATE,Xuhao)
		    Values
		    (@NEWID,@YYYYMM,0,@NewItemBM,@balance,0,0,@balance,@Detailflag,'本期合计',@BenYueLastDay,'88888888')  
	            END     
		    else
		    begin	


--                       rawdebit = ( select isnull(sum(rawdebit),0) from  #CW_INITBALA_all 
--                                    where ItemBM like a.ItemBM +'%') ,
--			select SumBAMOUNT=isnull(sum(BAMOUNT),0),SumAMOUNT=isnull(sum(EAMOUNT),0), from  CW_BILLFLOW where ItemBM like @NewItemBM +'%'  and (rtrim(YYYYMMBILL) = 0) 

			update CW_BILLFLOW   set  BAMOUNT=( select isnull(sum(BAMOUNT),0) from  CW_BILLFLOW
                                    where ItemBM like @NewItemBM +'%'  and(rtrim(YYYYMMBILL) = 0) and Detailflag=1 ) ,
						  EAMOUNT=( select isnull(sum(EAMOUNT),0) from  CW_BILLFLOW
                                    where ItemBM like @NewItemBM +'%'  and(rtrim(YYYYMMBILL) = 0) and Detailflag=1 ) 					  						       
							 where 
             		                                    (rtrim(ItemBM) = @NewItemBM)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)

		    end			 ------IF   END

---	1、	yyyymmBill=0 ,本期起初、本期期末、本期收入合计、本期支出合计、

---	2、	yyyymmBill=2 ,本年起初、本年期末、本年收入累计、本期支出累计、

---     以上每个月都有一条

---     3、     yyyymmBill=3 ,本年收入累计、本期支出累计，启用帐套的记录，会计科目初始化的本年累计借方与贷方
------------------------------------------------------------------------------
	            IF not exists(select *  from CW_BILLFLOW  where 
             		                                    (rtrim(ItemBM) = @NewItemBM)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 2)       ---2代表本年合计记录
             		                                 )       
	            BEGIN
                     execute  GETKEYVALUE     'CW_BillFlow',@R_KeyValue = @NEWID output
		    insert into CW_BillFlow 
		    (ID,YYYYMM,YYYYMMBILL,ItemBM,
		     BAMOUNT,debit,credit,EAMOUNT,Detailflag,brief,BILLDATE,Xuhao)
		    Values
		    (@NEWID,@YYYYMM,2,@NewItemBM,@balance,@Debit,@Credit,0,@Detailflag,'本年累计',@BenYueLastDay,'99999999')  
	            END     
		    begin	
			update CW_BILLFLOW   set   Debit=( select isnull(sum(Debit),0) from  CW_BILLFLOW
                                    where ItemBM like @NewItemBM +'%'  and(rtrim(YYYYMMBILL) = 0) and Detailflag=1 ) , 					  						       
						  Credit=( select isnull(sum(Credit),0) from  CW_BILLFLOW
                                    where ItemBM like @NewItemBM +'%'  and(rtrim(YYYYMMBILL) = 0) and Detailflag=1 ),
						  BAMOUNT=( select isnull(sum(BAMOUNT),0) from  CW_BILLFLOW
                                   where ItemBM like @NewItemBM +'%'  and(rtrim(YYYYMMBILL) = 0) and Detailflag=1 ) 
						  where 
             		                                    (rtrim(ItemBM) = @NewItemBM)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 2)

		    end			 ------IF   END


------------------------

	            IF not exists(select *  from CW_BILLFLOW  where 
             		                                    (rtrim(ItemBM) = @NewItemBM)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 3)       ---2代表本年合计记录
             		                                 )       
	            BEGIN
                     execute  GETKEYVALUE     'CW_BillFlow',@R_KeyValue = @NEWID output
		    insert into CW_BillFlow 
		    (ID,YYYYMM,YYYYMMBILL,ItemBM,
		     BAMOUNT,debit,credit,EAMOUNT,Detailflag,brief,BILLDATE)
		    Values
		    (@NEWID,@YYYYMM,3,@NewItemBM,0,@Debit,@Credit,0,@Detailflag,'会计科目初始化本年累计',@BenYueLastDay)  
	            END     
		    begin	
			update CW_BILLFLOW   set  Debit=( select isnull(sum(Debit),0) from  CW_BILLFLOW
                                    where ItemBM like @NewItemBM +'%'  and(rtrim(YYYYMMBILL) = 0) and Detailflag=1 ) , 					  						       
						  Credit=( select isnull(sum(Credit),0) from  CW_BILLFLOW
                                    where ItemBM like @NewItemBM +'%'  and(rtrim(YYYYMMBILL) = 0) and Detailflag=1 ) 					  						       

						        where  (rtrim(ItemBM) = @NewItemBM)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 3)

		    end			 ------IF   END




------------------------

	        select @PrevNO=PrevNO from ItemInfo where ItemBM=@NewItemBM


		SET @NewItemBM=@PrevNO

	     end          -------while  @PrevNO<>'0000' 

	    fetch Cur_CLIENT_100 into    @ItemBM,@Debit, @Credit,@balance
       END


	    close Cur_CLIENT_100
	    deallocate Cur_CLIENT_100


----------------------------------------------------------------------------------

  update   accoptionS  set optionvalue = @START_YYYYMM          where optionname ='CW_YYYYMM'
  update   ACCINFO     set CW_STARTDATE= @START_YYYYMMDD , CW_STATUS= 1, CW_STARTYYYYMM= @START_YYYYMM         where GUID ='0001'
     



--------取得接转当前会计期间的数据并复制到临时表中 end ------------------------------------



--写结转信息
  If @@error = 0
  begin
     commit transaction CW_Start
   set @IsSuccess=1
  end
  else
  begin
    rollback transaction CW_Start
   set @IsSuccess=0
    raiserror('结转失败 ', 1, 20) 
  end

















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG









--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[CW_Data_START_DEL] (
		              @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                              @IsSuccess         int output     ---返回成功  -- 0 不成功  --1 
                            )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
Begin transaction CWDataToNext_DEL
   declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月
   declare  @SQLSTR         varchar(8000)  -- 下一个会计年月


declare @YYYYMM varchar(6)                   --会计年月     
declare @Current_YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。


declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)


declare  @STATUS INTEGER
  


         	SET @STATUS =(select   ISNULL(CW_STATUS,0)   FROM  ACCINFO  WHERE GUID='0001')

            IF  @STATUS=0        ----帐套未启用
             BEGIN
		  commit transaction CWDataToNext_DEL         
	   	  set @IsSuccess=1
	          RETURN
             END


-----------检测是否有凭证登帐    

        if exists(Select * from CW_PingZhengM where flagpost=1)	        
	begin
		set @RETURNSTRING ='已经有凭证登帐，不能反启用帐套！'
	     commit transaction CWDataToNext_DEL         
	   	   set @IsSuccess=0
	             RETURN

	end

	delete CW_BILLFLOW

----------------------------------------------------------------------------------

  update   accoptionS  set optionvalue = ''                         where optionname ='CW_YYYYMM'
  update   ACCINFO     set CW_STARTDATE= NULL,CW_STATUS= 0,CW_STARTYYYYMM= NULL          where GUID ='0001'
     



--------取得接转当前会计期间的数据并复制到临时表中 end ------------------------------------



--写结转信息
  If @@error = 0
  begin
     commit transaction CWDataToNext_DEL
   set @IsSuccess=1
  end
  else
  begin
    rollback transaction CWDataToNext_DEL
   set @IsSuccess=0
    raiserror('反启用帐套 ', 1, 20) 
  end















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG
















CREATE PROCEDURE [dbo].[CW_DengZhang]  
                 (
                  @BILLPost varchar(20)
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION

AS 
 
declare @BILLID  varchar(60)
declare @YYYYMM  varchar(10)
declare @INAMOUNT  NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @SUMBAMOUNT NUMERIC(20,10)            ---本期期初总金额
declare     @RETURNSTRINGXX    varchar(60)   
declare     @flagreturnXX int 
 
BEGIN

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='CW_YYYYMM')     

----------------------------------------------------------------

	    delete   CW_PingZhengD    where (ItemBM IS NULL  OR Len(ItemBM) <2 ) and  ( ISNULL(debit,0) =0  or  ISNULL(Credit,0)=0) 

------------登帐之前判断新增加的会计科目


--	    Select ItemBM from CW_PingZhengD where (BILLID IN (Select BILLID from CW_PingZhengM   where rtrim(YYYYMM) = @YYYYMM))
--						AND (ItemBM NOT IN (Select ITemBM From CW_BILLFLOW where YYYYMM = @YYYYMM and YYYYMMBILL=0))


------------------------------现金流数据准备
			update CW_PingZhengM set   CashMustFlag = 1
			where BILLID In (Select BILLID  From CW_PingZhengD  Where ItemBM In   (Select ItemBM  From ItemInfo Where XJLL=1))
------------------------------现金流数据准备

			

	    declare CW_DengZhang_Cursor Cursor for Select BILLID from CW_PingZhengM   where rtrim(YYYYMM) = @YYYYMM and FlagCheck=1
            		      ORDER BY BILLDATE

	    Open CW_DengZhang_Cursor

	    fetch CW_DengZhang_Cursor into @BILLID


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin


---		exec STORE_CW_PingZheng '00000002',@RETURNSTRINGXX,@flagreturnXX
		exec STORE_CW_PingZheng  @BILLID,@BILLPost,@RETURNSTRINGXX,@flagreturnXX

------------------------------现金流数据准备
			update CW_PingZhengM   set  CashDebit=( select isnull(sum(Debit),0) from  CW_PingZhengD
                                    where ItemBM In   (Select ItemBM  From ItemInfo Where XJLL=1) and BILLID=@BILLID ) ,
				  CashCredit=( select isnull(sum(Credit),0) from  CW_PingZhengD
                                    where ItemBM In   (Select ItemBM  From ItemInfo Where XJLL=1) and BILLID=@BILLID ) 					  						       
			where BILLID=@BILLID

------------------------------现金流数据准备
-------------------------------


---		print	@BILLID
---		print	@RETURNSTRINGXX
---		print	@flagreturnXX

		---select @RETURNSTRINGXX
		---select @flagreturnXX 

		    fetch CW_DengZhang_Cursor into @BILLID
 
	    END           ------- CW_DengZhang_Cursor  WHILE

	    close CW_DengZhang_Cursor
	    deallocate CW_DengZhang_Cursor

-----------------------------------------------------------------------------------------------------------------------------------------------------------
------------------------------现金流数据准备
			update CW_PingZhengM set   CashMustFlag = 0
			where CashDebit=CashCredit
------------------------------删除数据现金自身流转的
------------------------------现金流数据准备
		update CW_BILLFLOW set JHD= b.JHD  from CW_BILLFLOW a , iteminfo b where a.Itembm=b.Itembm
-------------------------------------------------------------------

END





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












CREATE PROCEDURE [dbo].[CW_DengZhang_DEL]  
AS 
 
declare @BILLID  varchar(60)
declare @INAMOUNT  NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @SUMBAMOUNT NUMERIC(20,10)            ---本期期初总金额
declare @RETURNSTRINGXX    varchar(60)   
declare @flagreturnXX int 
declare @YYYYMM  varchar(10)

 
BEGIN

----------------------------------------------------------------
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='CW_YYYYMM')     

	    declare CW_DengZhang_DEL_Cursor Cursor for Select BILLID from CW_PingZhengM   where rtrim(YYYYMM) = @YYYYMM and FlagPost=1
            		      ORDER BY BILLDATE

	    Open CW_DengZhang_DEL_Cursor

	    fetch CW_DengZhang_DEL_Cursor into @BILLID


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin


---		exec STORE_CW_PingZheng_DEL '00000002',@RETURNSTRINGXX,@flagreturnXX
		exec STORE_CW_PingZheng_DEL @BILLID,@RETURNSTRINGXX,@flagreturnXX

		---select @RETURNSTRINGXX
		---select @flagreturnXX 

		    fetch CW_DengZhang_DEL_Cursor into @BILLID
 
	    END           ------- CW_DengZhang_DEL_Cursor  WHILE

	    close CW_DengZhang_DEL_Cursor
	    deallocate CW_DengZhang_DEL_Cursor

-----------------------------------------------------------------------------------------------------------------------------------------------------------


END




----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













------------------

CREATE PROCEDURE [dbo].[CW_GET_ItemInfo_ItemBM] (
                  @PrevNO varchar(50),
                  @bill_no_selfd varchar(50) output, --单号
		  @NextItemBMLen  INt  output
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --当前会计年月     
declare @idd varchar(50)
declare @HouBuidd varchar(50)                     --序列号
declare @BILLNOFLAG  varchar(1)                     --单据格式
declare @BILLW  varchar(20)                     --单据格式
declare @YYYYMM_FLAG  INTEGER
declare @Step0 int
declare @Step1 int
declare @Step2 int
declare @Step3 int
declare @Step4 int
declare @Step5 int
declare @Step6 int
declare @Step7 int
declare @Step8 int
declare @Step9 int

begin

---      select   @idd = (select max(substring(ItemBM,len(@PrevNO)+1,len(ItemBM)-len(@PrevNO))) as maxid from ItemInfo where PrevNO=@PrevNO)

	if @PrevNO='0000'
	begin
	      set  @bill_no_selfd =''
		return
	end

      select   @idd = (select max(ItemBM) as maxid from ItemInfo where PrevNO=@PrevNO)
--      select   @idd = (select max(substring(CODE,12,4)) as maxid from STOREZZHPM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
	set @HouBuIdd='1'+substring(@idd,len(@PrevNO)+1,len(@idd)-len(@PrevNO))

      set      @HouBuIdd = rtrim(convert(char,convert(int,@HouBuIdd)+1))
		
      set      @bill_no_selfd =substring(@HouBuidd,2,len(@HouBuidd)-1)



	select @Step0=Step0,@Step1=Step1,@Step2=Step2,@Step3=Step3,@Step4=Step4,@Step5=Step5,@Step6=Step6,@Step7=Step7,
		@Step8=Step8,@Step9=Step9  FROM  ACCINFO  WHERE GUID='0001'


            IF   Len(@PrevNO)=@Step0 
	    begin
		SET @NextItemBMLen=@Step1 
	    end

            IF   Len(@PrevNO)=@Step0+@Step1  
	    begin
		SET @NextItemBMLen=@Step2 
	    end
            IF   Len(@PrevNO)=@Step0+@Step1+@Step2   
	    begin
		SET @NextItemBMLen=@Step3 
	    end
            IF   Len(@PrevNO)=@Step0+@Step1+@Step2+@Step3
	    begin
		SET @NextItemBMLen=@Step4 
	    end

            IF   Len(@PrevNO)=@Step0+@Step1+@Step2+@Step3+@Step4
	    begin
		SET @NextItemBMLen=@Step5 
	    end
            IF   Len(@PrevNO)=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5
	    begin
		SET @NextItemBMLen=@Step6 
	    end
            IF   Len(@PrevNO)=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6
	    begin
		SET @NextItemBMLen=@Step7 
	    end
            IF   Len(@PrevNO)=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7
	    begin
		SET @NextItemBMLen=@Step8 
	    end
            IF   Len(@PrevNO)=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7+@Step8
	    begin
		SET @NextItemBMLen=@Step9 
	    end





end







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













----------------------------------------------------------------------------
CREATE PROCEDURE [CW_GET_Next_Item_len]  (  @PrevNO varchar(30),      ---单据编号   
	     @NextItemBMLen  INt  output)     --APSOFTENCRYPTION       WITH ENCRYPTION
AS 


declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @STOREHSFS   INTEGER
declare @MAXID   varchar(30)
declare @Step0 int
declare @Step1 int
declare @Step2 int
declare @Step3 int
declare @Step4 int
declare @Step5 int
declare @Step6 int
declare @Step7 int
declare @Step8 int
declare @Step9 int
 
BEGIN

	select @Step0=Step0,@Step1=Step1,@Step2=Step2,@Step3=Step3,@Step4=Step4,@Step5=Step5,@Step6=Step6,@Step7=Step7,
		@Step8=Step8,@Step9=Step9  FROM  ACCINFO  WHERE GUID='0001'


            IF   Len(@PrevNO)=@Step0  and @PrevNO<>'0000'
	    begin
		SET @NextItemBMLen=@Step1 
	    end
	    else
	    begin
		SET @NextItemBMLen=@Step0 
	    end

	    
            IF   Len(@PrevNO)=@Step0+@Step1  
	    begin
		SET @NextItemBMLen=@Step2 
	    end
            IF   Len(@PrevNO)=@Step0+@Step1+@Step2   
	    begin
		SET @NextItemBMLen=@Step3 
	    end
            IF   Len(@PrevNO)=@Step0+@Step1+@Step2+@Step3
	    begin
		SET @NextItemBMLen=@Step4 
	    end

            IF   Len(@PrevNO)=@Step0+@Step1+@Step2+@Step3+@Step4
	    begin
		SET @NextItemBMLen=@Step5 
	    end
            IF   Len(@PrevNO)=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5
	    begin
		SET @NextItemBMLen=@Step6 
	    end
            IF   Len(@PrevNO)=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6
	    begin
		SET @NextItemBMLen=@Step7 
	    end
            IF   Len(@PrevNO)=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7
	    begin
		SET @NextItemBMLen=@Step8 
	    end
            IF   Len(@PrevNO)=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7+@Step8
	    begin
		SET @NextItemBMLen=@Step9 
	    end


END
  








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG










CREATE PROCEDURE [dbo].[CW_GET_SUM] (@TableName  varchar(50),
				@BILLID  varchar(50),
				@GongShiStr  varchar(200),
				@ReturnAMT numeric(20, 2)  output)
AS 
  declare    @SqlSTR  varchar(1000)
  declare    @XX  varchar(1000)
  declare    @GongShiReturn  numeric(20, 2)
  declare    @SumAMT  numeric(20, 2)
   declare  @BeginMM int
   declare  @EndMM int
   declare  @MM int

BEGIN

 
Create Table #TempValue
      (   ABCD    varchar(50)  NULL
		)


	   Set  @BeginMM =Cast(SubString(@GongShiSTR,2,CHARINDEX(':',@GongShiSTR)-2) as INT)
	   set  @EndMM =Cast(SubString(@GongShiSTR,CHARINDEX(':',@GongShiSTR)+2,Len(@GongShiSTR)-CHARINDEX(':',@GongShiSTR)-1) as INT)


	   set  @MM=@BeginMM
		set @SumAMT=0

 		while  @MM<=@EndMM
		begin

			SET @SqlSTR=' delete  #TempValue  '
			exec (@SqlSTR)

			SET @SqlSTR=' INSERT  #TempValue  '
			SET @SqlSTR=@SqlSTR+' Select '+ SubString(@GongShiSTR,1,1)+' from '+@TableName+' where XuHao ='+Cast(@MM as Varchar(3))+' AND BILLID = '+@BILLID		

			exec (@SqlSTR)
				update #TempValue set ABCD=REPLACE(ABCD,',','')
				update #TempValue set ABCD=NULL  where Rtrim(Ltrim(ABCD))=''

				Select @XX=ABCD from  #TempValue


				Select @GongShiReturn=ISNULL(ABCD,0) from  #TempValue

				set @SumAMT=@SumAMT+ISNULL(@GongShiReturn,0)

		    set @MM=@MM+1

		end

	    set @ReturnAMT=@SumAMT


END





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG
















----   公式解析函数
----   2013.08.16

----   =ASC("SY,5101,本期贷方累计")-ASC("SY,5101,本期借方累计")

----   公式字符串示例  ASC("5101,201303,本期借方累计")

----   首先要解析字符串

----   需要定义函数来解决

----   解析   比如： C1+C2+D3+D4+D5+D6


CREATE PROCEDURE [dbo].[CW_GongShiZhiXing] (@TableName  varchar(50),@BILLID  varchar(50),@GongShiStr  varchar(2000),@YearMonth  varchar(10),@ReturnSTR varchar(100)  output)
AS 


BEGIN
   declare    @YYYYMM  varchar(6)
   declare    @MM  INT
   declare    @NN  INT
   declare    @KK  INT
   declare    @I  INT
   declare    @JJ  INT     ---------公式序数
   declare    @TempStr  varchar(2000)
   declare    @xx  varchar(2000)
   declare    @PrevFuHao  varchar(1)
   declare    @TempGongShi  varchar(200)
   declare    @SqlSTR  varchar(1000)
   declare    @ACCTCanShu  varchar(200)
   declare    @TempAMT money
   declare    @GongShiReturn  numeric(20, 2)



----   select  CHARINDEX(',','SY,5101,本期借方累计')
----   公式字符串示例  ASC("5101,201303,本期借方累计")
----   公式字符串示例  ACCT(5101,201308,本期借方累计)-ACCT(5101,201308,本期借方累计)+C2+D3
----   运算符合不支持（）
----   运算符合仅支持 + - * /


Create Table #TempGongshiValue
      (   ABCD    varchar(50)  NULL
		)




	  SET  @TempStr=@GongShiStr

	  Set @I=1
	  Set @JJ=1
	  Set @TempGongShi=''
	  Set @TempAMT=0
          set @PrevFuHao='B'  -----没有运算符号的时候
-----------第一个运算符的位置
----'ACCT(5101,201308,本期借方累计)'
  

	 while  @I < =Len(@TempStr)
	 begin
		If (SubString(@TempStr,@I,1) In ('+','-','*','/')) ---- OR (@I =Len(@TempStr))
		begin
------------------------计算
------------------------这个地方判断是什么公式
------------------------假如公式取得值  @GongShiReturn
------------------------首先判断是否ACCT 即判断公式性质
------------------------判断是否第一个函数
------------------------暂时不支持第一个为-负号
----ACCT(5101,本期贷方累计)-ACCT(5101,本期借方累计)

			Set  @MM= CHARINDEX('ACCT',@TempGongShi)
			IF @MM>0 
			begin
			  Set @ACCTCanShu=SuBstring(@TempGongShi,6,Len(@TempGongShi)-6)   ----示例  5101,201308,本期借方累计
			   
			  select @GongShiReturn=DBO.ACCT(@ACCTCanShu,@YearMonth)

			end

			Set  @NN= CHARINDEX('SUM',@TempGongShi)        
			IF @NN>0 
			begin
			  Set @ACCTCanShu=SuBstring(@TempGongShi,5,Len(@TempGongShi)-5)   ----示例  5101,201308,本期借方累计

				Print @TempGongShi
			   
			  exec CW_GET_SUM @TableName,@BILLID,@ACCTCanShu,@GongShiReturn  output

			end



			Set  @KK= CHARINDEX('XJLL',@TempGongShi)               -----XJLL(10010,流入)
			IF @KK>0 
			begin
			  Set @ACCTCanShu=SuBstring(@TempGongShi,6,Len(@TempGongShi)-6)   ----示例  5101,201308,本期借方累计

				Print @TempGongShi
			   
			  select @GongShiReturn=DBO.XJLL(@ACCTCanShu,@YearMonth)
--				select @GongShiReturn=11

			end




-----------------------  SubString(@TempGongShi,1,1)
			IF (SubString(@TempGongShi,1,1) IN ('A','B','C','D','E','F','G','H','I','J','K','L','M','N')) AND @MM=0 AND @NN=0 AND @KK=0
			begin
			
				SET @SqlSTR=' delete  #TempGongshiValue  '
				exec (@SqlSTR)

				SET @SqlSTR=' INSERT #TempGongshiValue  '
				SET @SqlSTR=@SqlSTR+' Select '+ SubString(@TempGongShi,1,1)+' from '+@TableName+' where XuHao='+SubString(@TempGongShi,2,len(@TempGongShi)-1)+' AND BILLID = '+@BILLID		
				exec (@SqlSTR)
					update #TempGongshiValue set ABCD=REPLACE(ABCD,',','')
					update #TempGongshiValue set ABCD=NULL  where Rtrim(Ltrim(ABCD))=''


--				Select @XX=ABCD from  #TempGongshiValue

--					print @xx
				Select @GongShiReturn=ISNULL(ABCD,0) from  #TempGongshiValue

			end
				if @GongShiReturn iS NULL
				Select @GongShiReturn=0

			
------------------------取本表的单元格-----需要用表明传递参数

------------------------记住前一运算负号
------------------------写一个二次嵌套
			if @JJ<>1
			begin
				if  @PrevFuHao='+' 
				begin
				Set @TempAMT=@TempAMT+@GongShiReturn
				end
				if  @PrevFuHao='-' 
				begin
				Set @TempAMT=@TempAMT-@GongShiReturn
				end
				if  @PrevFuHao='*' 
				begin
				Set @TempAMT=@TempAMT*@GongShiReturn
				end
				if  @PrevFuHao='/' 
				begin
				Set @TempAMT=@TempAMT/@GongShiReturn
				end

			end
			else
			begin
			       set @TempAMT=@GongShiReturn
			       set @JJ=@JJ+1
			end
		        set @PrevFuHao=SubString(@TempStr,@I,1)

			SET @TempGongShi=''
	
		end
		else
		begin
		  Set @TempGongShi=@TempGongShi+SubString(@TempStr,@I,1)
		end
	  Set @I=@I+1
	 end 
---------------------------------------------------
---------------------------------------------------
		if @I =Len(@TempStr)+1  ----符号后最后一个
		begin


			Set  @MM= CHARINDEX('ACCT',@TempGongShi)
			IF @MM>0 
			begin
			  Set @ACCTCanShu=SuBstring(@TempGongShi,6,Len(@TempGongShi)-6)   ----示例  5101,201308,本期借方累计
			   
			  select @GongShiReturn=DBO.ACCT(@ACCTCanShu,@YearMonth)

			end

			Set  @NN= CHARINDEX('SUM',@TempGongShi)              
			IF @NN>0 
			begin
				Print cast(@NN as varchar(10))
			  Set @ACCTCanShu=Substring(@TempGongShi,5,Len(@TempGongShi)-5)   ----示例  5101,201308,本期借方累计
				Print @TempGongShi
			   
			  exec CW_GET_SUM @TableName,@BILLID,@ACCTCanShu,@GongShiReturn  output

			end

			Set  @KK= CHARINDEX('XJLL',@TempGongShi)               -----XJLL(10010,流入)
			IF @KK>0 
			begin
			  Set @ACCTCanShu=SuBstring(@TempGongShi,6,Len(@TempGongShi)-6)   ----示例  5101,201308,本期借方累计

				Print @TempGongShi
			   
			  select @GongShiReturn=DBO.XJLL(@ACCTCanShu,@YearMonth)
--				select @GongShiReturn=11

			end





			IF (SubString(@TempGongShi,1,1) IN ('A','B','C','D','E','F','G','H','I','J','K','L','M','N')) AND @MM=0 AND @NN=0 AND @KK=0
			begin
			
				SET @SqlSTR=' delete  #TempGongshiValue  '
				exec (@SqlSTR)

				SET @SqlSTR=' INSERT #TempGongshiValue  '
				SET @SqlSTR=@SqlSTR+' Select '+ SubString(@TempGongShi,1,1)+' from '+@TableName+' where XuHao='+SubString(@TempGongShi,2,len(@TempGongShi)-1)+' AND BILLID = '+@BILLID				
--				print @SqlSTR
				exec (@SqlSTR)
					update #TempGongshiValue set ABCD=REPLACE(ABCD,',','')
					update #TempGongshiValue set ABCD=NULL  where Rtrim(Ltrim(ABCD))=''


--				Select @XX=ABCD from  #TempGongshiValue

--					print @xx
				Select @GongShiReturn=ISNULL(ABCD,0) from  #TempGongshiValue

			end
			
				if @GongShiReturn iS NULL
				Select @GongShiReturn=0




				if  @PrevFuHao='+' 
				begin
				Set @TempAMT=@TempAMT+@GongShiReturn
				end
				if  @PrevFuHao='-' 
				begin
				Set @TempAMT=@TempAMT-@GongShiReturn
				end
				if  @PrevFuHao='*' 
				begin
				Set @TempAMT=@TempAMT*@GongShiReturn
				end
				if  @PrevFuHao='/' 
				begin
				Set @TempAMT=@TempAMT/@GongShiReturn
				end
				if  @PrevFuHao='B'      --只有一个函数的时候
				begin
				Set @TempAMT=@GongShiReturn
				end
		end


--	Select @ReturnSTR = Cast(@TempAMT as varchar(100))  
	Select @ReturnSTR = CONVERT(varchar(100),@TempAMT,1)
		print @ReturnSTR


END











----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG

























--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE [dbo].[CW_INOUTMXB](@ItemBM varchar(30) ,                        -----如果为0000则全部仓库
                                                                                            @Begin_YYYYMM   varchar(10) ,
                                                                                           @End_YYYYMM   varchar(10) 
                        
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @End_YYYYMMAddone  datetime,
        @MAXBILLDATE  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
	@VENDOR_CLIENT_ID  varchar(20),
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8),
        @WHERESTING   varchar(1800)

declare @BANKNAME  varchar(50)
declare @ClientNAME  varchar(50)
declare @BANKSTR  varchar(50)
declare @STRZhaiYao   varchar(300)      -------收款方式、收款去向
declare @Memo   varchar(300)      -------收款方式、收款去向


declare @ID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare  @BILLTYPE  INTEGER
declare @BILLCODE  nvarchar(50)
declare @BILLDATE  datetime
declare @BILLTYPENAME  nvarchar(50)
declare @Begin_Date  varchar(10)
declare @Debit NUMERIC(20,10)
declare @Credit NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @EAMOUNTPREV NUMERIC(20,10)
---//==========
declare @BAMOUNT NUMERIC(20,10)
declare @MAXID  nvarchar(50)
declare @JHD  INT



                   set @now_date=(select   max(billDATE)   FROM CW_billflow)

		set @Begin_Date=substring(@Begin_YYYYMM,1,4)+'-'+substring(@Begin_YYYYMM,5,2)+'-01'

		update CW_BILLFLOW  set xuhao=ID  where xuhao is null   and  YYYYMMBILL=1
                       

                          SELECT    @WHERESTING  = '  AND     YYYYMM >='+char(39)+@Begin_YYYYMM+char(39)+' and  YYYYMM <='+char(39)+ @End_YYYYMM+char(39) 
                          SELECT    @BANKSTR  = '  AND     ItemBM ='+char(39)+@ItemBM+char(39)


     

Create Table #temptable1
      (ID  varchar(20) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
   YYYYMM  varchar(50)  NULL,
   xuhao  varchar(50)  NULL,
	[Debit] NUMERIC(20,10)  NULL ,
	[Credit] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
   zhaiyao  varchar(200)  NULL
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   ID , BILLID,BILLTYPE,BILLCODE,BILLDATE,BILLTYPE,YYYYMM,xuhao,  '
           SELECT  @SQLSTR = @SQLSTR+'Debit,Credit,EAMOUNT ,brief '
           SELECT  @SQLSTR = @SQLSTR+'  from CW_billflow   where yyyymmbill in (0,1,2)    '  + @WHERESTING+@BANKSTR 
           SELECT  @SQLSTR = @SQLSTR+'  order by id '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(20) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
   JHD int  NULL,
	[Debit] NUMERIC(20,10)  NULL ,
	[Credit] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
    zhaiyao nvarchar(300)  NULL,
    Memo nvarchar(300)  NULL,
		)


---------------------------------------------------
		select @JHD=JHD  from ItemInfo where ItemBM=@ItemBM

	          set @COUNTID='00000001'
	   if exists (Select  ID,BILLID,BILLTYPE, BILLCODE,BILLDATE,BILLTYPENAME,
                                                     isnull(Debit,0) as Debit ,  isnull(Credit,0) as Credit ,
                                                     isnull(EAMOUNT,0) as EAMOUNT   from  #temptable1        )
                 begin
	    declare INOUTMXBREP Cursor for Select  ID,BILLID,BILLTYPE , BILLCODE,BILLDATE,BILLTYPENAME,
                                                       isnull(Debit,0) as Debit ,   isnull(Credit,0) as Credit ,
                                                     isnull(EAMOUNT,0) as EAMOUNT ,zhaiyao  from  #temptable1         ORDER BY YYYYMM,BILLDATE,xuhao
	    Open INOUTMXBREP

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @Debit,@Credit,@EAMOUNT,@STRZhaiYao

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                        SELECT  @MAXID=ID  FROM CW_billflow  WHERE  ItemBM=@ItemBM  AND YYYYMM=@Begin_YYYYMM   AND YYYYMMBILL=0
                        IF @MAXID IS NULL
 			BEGIN
			SET  @BAMOUNT=0
			END
                        ELSE
			BEGIN
	                           SELECT @BAMOUNT=BAMOUNT   FROM   CW_billflow  WHERE ID=@MAXID
			END
                                                              
                          INSERT    INTO   #temptable2  (ID,BILLDATE, zhaiyao,EAMOUNT,JHD)
                                           VALUES  (@COUNTID ,@Begin_Date, '期初余额',@BAMOUNT,@JHD)
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
                       SELECT  @BILLTYPENAME=NAME FROM  BILLNAME  WHERE @BILLTYPENAME=BILLTYPEID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID


                    INSERT    INTO   #temptable2  (ID,BILLID,BILLTYPE, BILLCODE,BILLDATE,BILLTYPENAME,
                                                               Debit,Credit,EAMOUNT,zhaiyao,Memo,JHD)
                                           VALUES  (@COUNTID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @Debit,@Credit,@EAMOUNT,@STRZhaiYao,@Memo,@JHD)

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @Debit,@Credit,@EAMOUNT,@STRZhaiYao
 

	    END           ------- INOUTMXBREP  WHILE
	    close INOUTMXBREP
	    deallocate INOUTMXBREP
        end     ------------  if exists
---------------------------
---------解决当前仓库本期间未发生业务的货品
--                  delete    #temptable1
            ELSE
            BEGIN

                        SELECT  @ID=ID  FROM CW_billflow  WHERE  ItemBM=@ItemBM  AND YYYYMM=@Begin_YYYYMM   AND YYYYMMBILL=0

	             	  SELECT    @ID=ID,@EAMOUNT=BAMOUNT    FROM  CW_billflow  WHERE    ID = @ID   


                 SELECT  @BANKNAME= FullName   FROM ItemInfo  WHERE ItemBM=@ItemBM
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME         )
                                           VALUES  (@COUNTID,@BANKNAME)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                                                              
                          INSERT    INTO   #temptable2  (ID ,billdate, zhaiyao,EAMOUNT)
                                           VALUES  (@COUNTID,@Begin_Date,'期初余额',@EAMOUNT)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期末结存',@EAMOUNT)

---------------------------
	END




--------------------------

 SELECT *  FROM #temptable2         ORDER BY ID
















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[CW_JieZhuanSY]  
                 (
		  @JieZhuanFlag  int ,    ----------- 1  
		  @DengZhangFlag  int ,    ----------- 0 不登帐  1登帐
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 

----损益科目结转金额始终以正数表示     @JieZhuanFlag=1
----损益科目结转方向与会计科目中定义的余额方向相反   @JieZhuanFlag=2

declare @YYYYMM varchar(6)                   --会计年月     
declare  @INF_COSTINGTYPEID  INT
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @BenNianLRKeMu  varchar(30) 
declare @CLIENTID varchar(10)                   --单句会计年月     
declare @ITEMNO varchar(15)               --明细存货编号
declare @ITEMNO00 varchar(15)               --明细存货编号
declare @ItemBM varchar(30)               --明细存货编号
declare @XuHao varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @MM   INT          --明细存货编号
declare @JHD   INT          --明细存货编号
declare @A   varchar(500)               --明细存货编号
declare @B   varchar(500)               --明细存货编号
declare @C   varchar(500)               --明细存货编号
declare @D   varchar(500)               --明细存货编号
declare @E   varchar(500)               --明细存货编号
declare @YearMonth  varchar(6)
declare @BILLTYPE   INTEGER
declare @SFLAG   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @EAMOUNT NUMERIC(20,2)
declare @Debit NUMERIC(20,2)
declare @Credit NUMERIC(20,2)
declare @BILLID_1 varchar(20)                   --单句会计年月     
declare @BILLID_2 varchar(20)                   --单句会计年月     
declare @CredTypeID int
declare @CredCode  int
declare @CredNO  int


                                              SET @RETURNSTRING='   '



     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CW_JieZhuanSY   --事物开始


-----------先检测凭证是否全部记账

	     set @YYYYMM   = (select optionvalue from accoptions where optionname ='CW_YYYYMM')     

	 if  exists(Select * from CW_PingZhengM where YYYYMM= @YYYYMM AND ISNULL(FlagPost,0)=0)

	  begin
		      rollback transaction trans_CW_JieZhuanSY
		      set  @flagreturn = 0
	              SET  @RETURNSTRING='本会计期间有未登帐的凭证，不能进行结转损益！'

	  end

-----@BenNianLRKeMu='3131'
	select @BenNianLRKeMu=BenNianLRKeMu  FROM  ACCINFO  WHERE GUID='0001'


----------如果正数或负数

----------同时生成两张单据，保存相反的方向

----------先生成两张空单据，一个是本年利润是借方，一个是本年利润为贷方

----------记住这两个的单据的ID那样能解决问题，


	     execute  GET_CWPZ_BILLID  @BILLID_1 output
	     set @BILLDATE= CONVERT(varchar(100), dateadd(day,-1,dateadd(Month,1,Cast(substring(@YYYYMM,1,4)+'-'+Substring(@YYYYMM,5,2)+'-01' as datetime))), 23)
-------------本月最后一天
	     SET @CredTypeID=1

             exec GET_Cred_Code_NO 1 ,@CredNo output,@CredCode output

            INSERT  INTO CW_PingZhengM (BILLID,YYYYMM,MAKEMAN,BILLDATE,CredTypeID,CredNo,CredCode,FlagCheck,BILLCheck)
		    VALUES (@BILLID_1,@YYYYMM,'机制',@BILLDATE,@CredTypeID,@CredNo,@CredCode,1,'机制')

            execute  GETKEYVALUE   'CW_PingZhengD',@R_KeyValue = @ITEMNO00 output


            INSERT  INTO CW_PingZhengD (BILLID,ITEMNO,ItemBM,Brief,debit,Credit)
		    VALUES (@BILLID_1,@ITEMNO00,@BenNianLRKeMu,'结转本期损益',0,0)

------------第一张单据，本年利润为借方
---------------以上是生成第一张单据


	     execute  GET_CWPZ_BILLID  @BILLID_2 output


             exec GET_Cred_Code_NO 1 ,@CredNo output,@CredCode output


            INSERT  INTO CW_PingZhengM (BILLID,YYYYMM,MAKEMAN,BILLDATE,CredTypeID,CredNo,CredCode,FlagCheck,BILLCheck)
		    VALUES (@BILLID_2,@YYYYMM,'机制',@BILLDATE,@CredTypeID,@CredNo,@CredCode,1,'机制')

            execute  GETKEYVALUE   'CW_PingZhengD',@R_KeyValue = @ITEMNO00 output


            INSERT  INTO CW_PingZhengD (BILLID,ITEMNO,ItemBM,Brief,debit,Credit)
		    VALUES (@BILLID_2,@ITEMNO00,@BenNianLRKeMu,'结转本期损益',0,0)


-----------------------

    declare Cursor_CW_JiezhanSY Cursor for Select ItemBM,JHD,EAMOUNT from CW_BILLFLOW where DetailFlag=1 and YYYYMMBILL=0 AND YYYYMM=@YYYYMM
				AND  Itembm Like '5%'  AND JHD=1  and ISNULL(Eamount,0)<>0
				Order By Itembm
    Open Cursor_CW_JiezhanSY

    fetch Cursor_CW_JiezhanSY into @ItemBM,@JHD,@EAMOUNT

    while @@fetch_status = 0            ----开始
    begin

            execute  GETKEYVALUE   'CW_PingZhengD',@R_KeyValue = @ITEMNO00 output

	    IF @JieZhuanFlag=1
	    begin
		    IF @EAMOUNT>0
		    begin
	        	    INSERT  INTO CW_PingZhengD (BILLID,ITEMNO,ItemBM,Brief,debit,Credit)
			    VALUES (@BILLID_1,@ITEMNO00,@ItemBM,'结转本期损益',0,@EAMOUNT)
		    end
		    IF @EAMOUNT<0
		    begin
		            INSERT  INTO CW_PingZhengD (BILLID,ITEMNO,ItemBM,Brief,debit,Credit)
			    VALUES (@BILLID_2,@ITEMNO00,@ItemBM,'结转本期损益',abs(@EAMOUNT),0)
		    end
	    end

	    IF @JieZhuanFlag=2
	    begin
        	    INSERT  INTO CW_PingZhengD (BILLID,ITEMNO,ItemBM,Brief,debit,Credit)
		    VALUES (@BILLID_1,@ITEMNO00,@ItemBM,'结转本期损益',0,@EAMOUNT)
	    end


    fetch Cursor_CW_JiezhanSY into @ItemBM,@JHD,@EAMOUNT

    END           ------- Cursor_CW_JiezhanSY  WHILE

    close Cursor_CW_JiezhanSY
    deallocate Cursor_CW_JiezhanSY
--------------------------------------结转损益类科目借方余额，损益科目结转金额始终以正数表示
    declare Cursor_CW_SY Cursor for Select ItemBM,JHD,EAMOUNT from CW_BILLFLOW where DetailFlag=1 and YYYYMMBILL=0 AND YYYYMM=@YYYYMM
				AND  Itembm Like '5%'  AND JHD=-1  and ISNULL(Eamount,0)<>0
				Order By Itembm
    Open Cursor_CW_SY

    fetch Cursor_CW_SY into @ItemBM,@JHD,@EAMOUNT

    while @@fetch_status = 0            ----开始
    begin

            execute  GETKEYVALUE   'CW_PingZhengD',@R_KeyValue = @ITEMNO00 output
	    IF @JieZhuanFlag=1
	    begin
		    IF @EAMOUNT>0
		    begin
        	    INSERT  INTO CW_PingZhengD (BILLID,ITEMNO,ItemBM,Brief,debit,Credit)
			    VALUES (@BILLID_2,@ITEMNO00,@ItemBM,'结转本期损益',@EAMOUNT,0)
		    end
		    IF @EAMOUNT<0
		    begin
        	    INSERT  INTO CW_PingZhengD (BILLID,ITEMNO,ItemBM,Brief,debit,Credit)
			    VALUES (@BILLID_1,@ITEMNO00,@ItemBM,'结转本期损益',0,abs(@EAMOUNT))
		    end
	    end
	    IF @JieZhuanFlag=2
	    begin
        	    INSERT  INTO CW_PingZhengD (BILLID,ITEMNO,ItemBM,Brief,debit,Credit)
			    VALUES (@BILLID_2,@ITEMNO00,@ItemBM,'结转本期损益',@EAMOUNT,0)
	    end

    fetch Cursor_CW_SY into @ItemBM,@JHD,@EAMOUNT

    END           ------- Cursor_CW_SY  WHILE

    close Cursor_CW_SY
    deallocate Cursor_CW_SY
--------------------------------------结转损益类科目贷方余额，损益科目结转金额始终以正数表示
	select @debit=sum(Credit) from CW_PingZhengD where BILLID=@BILLID_1
	select @Credit=sum(debit) from CW_PingZhengD where BILLID=@BILLID_2

	update CW_PingZhengD set debit=@debit  where BILLID=@BILLID_1  and itemBM=@BenNianLRKeMu
	update CW_PingZhengD set Credit=@Credit  where BILLID=@BILLID_2   and itemBM=@BenNianLRKeMu
---------解决已经结转还结转的操作
---------或者在程序顶部检测是否已经结转
	delete  CW_PingZhengM where BILLID IN (select BILLID from CW_PingZhengD where itemBM=@BenNianLRKeMu and ISNULL(debit,0) =0  and ISNULL(credit,0)=0 )

--------------
        IF @DengZhangFlag=1
	begin
	  exec CW_DengZhang  '机制'
	end

------------------------------------以上是删除全部单据明细

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CW_JieZhuanSY
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CW_JieZhuanSY
      set @flagreturn = 0
   end








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG










--------------------------------------------------------------------
CREATE PROCEDURE [dbo].[CW_KeMuYuEHZB](@BeginItemBM varchar(30) ,                        -----如果为0000则全部仓库
					    @ENDItemBM varchar(30) ,                        -----如果为0000则全部仓库
                                                                                            @Begin_YYYYMM   varchar(10) ,
                                                                                           @End_YYYYMM   varchar(10), 
                        				            @KeMuJiBie  int		

                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @End_YYYYMMAddone  datetime,
        @MAXBILLDATE  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
	@VENDOR_CLIENT_ID  varchar(20),
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8),
        @WHERESTING   varchar(1800)

declare @BANKNAME  varchar(50)
declare @ClientNAME  varchar(50)
declare @BANKSTR  varchar(500)
declare @STRZhaiYao   varchar(300)      -------收款方式、收款去向
declare @Memo   varchar(300)      -------收款方式、收款去向
declare @KeMuLenSTR  varchar(500)


declare @ID  varchar(50)
declare @BILLID  varchar(50)
declare @BILLTYPE  INTEGER
declare @NewYYYYMM  varchar(50)
declare @YYYYMM    varchar(50)
declare @BILLCODE  varchar(50)
declare @ItemBM    varchar(50)
declare @ItemBM00  varchar(50)
declare @BILLDATE  datetime
declare @Begin_Date  varchar(10)
declare @Debit NUMERIC(20,2)
declare @Credit NUMERIC(20,2)
declare @EAMOUNT NUMERIC(20,2)
declare @EAMOUNTPREV NUMERIC(20,2)
---//==========
declare @BAMOUNT NUMERIC(20,2)
declare @MAXID  varchar(50)
declare @KeMuLen  INT

declare @Step0 int
declare @Step1 int
declare @Step2 int
declare @Step3 int
declare @Step4 int
declare @Step5 int
declare @Step6 int
declare @Step7 int
declare @Step8 int
declare @Step9 int



                   set @now_date=(select   max(billDATE)   FROM CW_billflow)

		set @Begin_Date=substring(@Begin_YYYYMM,1,4)+'-'+substring(@Begin_YYYYMM,5,2)+'-01'

		update CW_BILLFLOW set jhd=b.jhd from CW_BILLFLOW a ,ItemInfo b where a.itembm=b.itembm

----------------第二个会计期间新增会计科目问题

----------------关于年中新增会计科目，增加新增会计科目的月结记录



                          SELECT    @BANKSTR  = '  AND     I.ItemBM >='+char(39)+@BeginItemBM+char(39)+'  AND  I.ItemBM <='+char(39)+@ENDItemBM+char(39)

                          SELECT    @WHERESTING  = '  AND     YYYYMM >='+char(39)+@Begin_YYYYMM+char(39)+' and  YYYYMM <='+char(39)+ @End_YYYYMM+char(39) 


	select @Step0=Step0,@Step1=Step1,@Step2=Step2,@Step3=Step3,@Step4=Step4,@Step5=Step5,@Step6=Step6,@Step7=Step7,
		@Step8=Step8,@Step9=Step9  FROM  ACCINFO  WHERE GUID='0001'



	IF @KeMuJiBie=1
	begin
		set @KeMuLen=@Step0
	end
	IF @KeMuJiBie=2
	begin
		set @KeMuLen=@Step0+@Step1
	end
	IF @KeMuJiBie=3
	begin
		set @KeMuLen=@Step0+@Step1+@Step2
	end
	IF @KeMuJiBie=4
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3
	end
	IF @KeMuJiBie=5
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4
	end
	IF @KeMuJiBie=6
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5
	end
	IF @KeMuJiBie=7
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6
	end
	IF @KeMuJiBie=8
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7
	end
	IF @KeMuJiBie=9
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7+@Step8
	end
	IF @KeMuJiBie=10
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7+@Step8+@Step9
	end


	SET @KeMuLenSTR	=' AND Len(I.ItemBM) <=  '+ Cast(@KeMuLen as Varchar(2))



     
---------------------------------------------------
		SELECT @SQLSTR='	select I.ITemBM,ISNULL(I.bamount,0)*I.JHD as bamount,E.Debit,E.Credit,(ISNULL(I.bamount,0)+(ISNULL(E.Debit,0)-ISNULL(E.Credit,0))*I.JHD)*I.JHD as Eamount,X.Debit as LeiJiDebit,X.Credit as LeiJiCredit  from  CW_BILLFLOW '
		SELECT @SQLSTR=@SQLSTR+'	 as I '
		SELECT @SQLSTR=@SQLSTR+'	 left outer join '
		SELECT @SQLSTR=@SQLSTR+'	 (select ITemBM,isnull(sum(Debit),0) as Debit ,isnull(sum(Credit),0) as Credit from  CW_BILLFLOW where  YYYYMMBILL=1 '+@WHERESTING
		SELECT @SQLSTR=@SQLSTR+'		Group BY ITemBM 	'
		SELECT @SQLSTR=@SQLSTR+'	 ) as E ON E.ITemBM=I.ITemBM '
		SELECT @SQLSTR=@SQLSTR+'	 left outer join  '
		SELECT @SQLSTR=@SQLSTR+'	 (select ITemBM,isnull(Debit,0) as Debit ,isnull(Credit,0) as Credit from  CW_BILLFLOW where  YYYYMMBILL=2 ' +'and  YYYYMM ='+char(39)+ @End_YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+'	 ) as X ON X.ITemBM=I.ITemBM '
		SELECT @SQLSTR=@SQLSTR+'	where yyyymmbill=0   AND     YYYYMM = '+char(39)+@Begin_YYYYMM+char(39)+@BANKSTR +@KeMuLenSTR	
		SELECT @SQLSTR=@SQLSTR+'	 Order by I.ITemBM '
------------------------------------------------------------------------
		EXEC(@SQLSTR)

















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












CREATE PROCEDURE [dbo].[CW_LRBMB_CRAET_CW_LRB](@BILLID varchar(8),                        -----如果为0000则全部仓库
						           @YearMonth   varchar(10),  
								   @RETURNSTRING    varchar(60)    output      ---单据编号   
                                                      )    --APSOFTENCRYPTION       WITH ENCRYPTION
as
declare @CODE00   [varchar] (25)   
declare @NewBILLID   varchar (50)   
declare @SFLAG  INTEGER
declare @BILLTYPE   INTEGER
declare @NewBILLDATE DATEtime


-------利润表的模板是唯一的，所以不需要传递参数  @BILLID

-----	select @BILLID = BILLID from STORECW_LRBMBM


	EXEC CW_BILL_XuHao_ChongPai 'STORECW_LRBMBD',@BILLID

	delete STORECW_LRBM  WHERE YearMonth=@YearMonth

----------如果存在就删除
	
	INSERT INTO STORECW_LRBM
	SELECT *  FROM  STORECW_LRBMBM WHERE BILLID=@BILLID

	INSERT INTO STORECW_LRBD
	SELECT *  FROM  STORECW_LRBMBD WHERE BILLID=@BILLID


	UPDATE STORECW_LRBM SET CODE=Substring(@YearMonth,1,4)+'年'+Substring(@YearMonth,5,2)+'月',
				YearMonth=@YearMonth,BillDate=getdate() WHERE BILLID=@BILLID


	UPDATE STORECW_LRBM SET BILLID=@YearMonth+BILLID   WHERE BILLID=@BILLID 
	UPDATE STORECW_LRBD SET ItemNO=@YearMonth+ItemNO   WHERE BILLID=@YearMonth+@BILLID


	SET @NewBILLID=@YearMonth+@BILLID
	declare @RETURNSTRING00  varchar(60) 
	declare @flagreturn00 int    ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
	exec CW_LRB_JiSuan  @NewBILLID,@RETURNSTRING00 ,@flagreturn00 output  

--	select @flagreturn




	SET @RETURNSTRING ='成功生成报表，表号为'+ @YearMonth
















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG










----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[CW_LRB_JiSuan]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare  @INF_COSTINGTYPEID  INT
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @CLIENTID varchar(10)                   --单句会计年月     
declare @ITEMNO varchar(15)               --明细存货编号
declare @XuHao varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @MM   INT          --明细存货编号
declare @A   varchar(500)               --明细存货编号
declare @B   varchar(500)               --明细存货编号
declare @C   varchar(500)               --明细存货编号
declare @D   varchar(500)               --明细存货编号
declare @E   varchar(500)               --明细存货编号
declare @YearMonth  varchar(6)
declare @BILLTYPE   INTEGER
declare @SFLAG   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @C_GongShi   varchar(500)               --明细存货编号
declare @D_GongShi   varchar(500)               --明细存货编号
declare @E_GongShi   varchar(500)               --明细存货编号
declare @C_Value   varchar(500)               --明细存货编号
declare @D_Value   varchar(500)               --明细存货编号
declare @E_Value   varchar(500)               --明细存货编号


                                              SET @RETURNSTRING='   '


	set @BILLID   = ltrim(rtrim(@BILLID))
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CW_LRB_DEL   --事物开始

     set @YearMonth =   (select YearMonth  from STORECW_LRBM where rtrim(BILLID) = @BILLID)


    declare SM_Consign_CW_LRB_DEL Cursor for Select ITEMNO,XuHao,A,B ,C,D,E   from STORECW_LRBD where rtrim(BILLID) = @BILLID  Order BY ITEMNO

    Open SM_Consign_CW_LRB_DEL

    fetch SM_Consign_CW_LRB_DEL into @ITEMNO,@XuHao,@A,@B,@C,@D,@E

    while @@fetch_status = 0            ----开始
    begin

--------------分别取C列与D列公式

		
		select @C_GongShi=C From STORECW_LRBMBD where XuHao=@XuHao

		select @D_GongShi=D From STORECW_LRBMBD where XuHao=@XuHao

		select @E_GongShi=E From STORECW_LRBMBD where XuHao=@XuHao



--     select PATINDEX('%[0-9]%', '234GHJ')
--     select PATINDEX('%[A-Fa-f]%', '234GHJ')
-----------------需要判断是否需要计算，是否是公式

			IF	CHARINDEX('ACCT',@C_GongShi)>0  OR 
				(PATINDEX('%[A-Na-n]%', @C_GongShi) >0 and PATINDEX('%[0-9]%', @C_GongShi) >0)
			begin
		                exec [dbo].[CW_GongShiZhiXing] 'STORECW_LRBD',@BILLID,@C_GongShi,@YearMonth, @C_Value output
			end
			else
			begin
		                SET @C_Value=@C_GongShi
			end
	
----------------------------------------------------			
			IF	CHARINDEX('ACCT',@D_GongShi)>0  OR 
				(PATINDEX('%[A-Na-n]%', @D_GongShi) >0 and PATINDEX('%[0-9]%', @D_GongShi) >0)
			begin
		                exec [dbo].[CW_GongShiZhiXing] 'STORECW_LRBD',@BILLID,@D_GongShi,@YearMonth, @D_Value output
			end
			else
			begin
		                SET @D_Value=@D_GongShi
			end
------------------------------------------------------	
			IF	CHARINDEX('ACCT',@E_GongShi)>0  OR 
				(PATINDEX('%[A-Na-n]%', @E_GongShi) >0 and PATINDEX('%[0-9]%', @E_GongShi) >0)
			begin
		                exec [dbo].[CW_GongShiZhiXing] 'STORECW_LRBD',@BILLID,@E_GongShi,@YearMonth, @E_Value output
			end
			else
			begin
		                SET @E_Value=@E_GongShi
			end
-------------------------------------------------------	

		update STORECW_LRBD SET C=@C_Value,D=@D_Value,E=@E_Value    where ItemNO=@ITEMNO

		update STORECW_LRBD SET C=NULL    where C='0.00'
		update STORECW_LRBD SET D=NULL    where D='0.00'
		update STORECW_LRBD SET E=NULL    where E='0.00'


-----CREATE PROCEDURE [dbo].[CW_GongShiZhiXing] (@TableName  varchar(50),@GongShiStr  varchar(2000),@YearMonth  varchar(10),@ReturnSTR varchar(100)  output)


--------------------
    fetch SM_Consign_CW_LRB_DEL into @ITEMNO,@XuHao,@A,@B,@C,@D,@E

    END           ------- SM_Consign_CW_LRB_DEL  WHILE

    close SM_Consign_CW_LRB_DEL
    deallocate SM_Consign_CW_LRB_DEL


------------------------------------以上是删除全部单据明细

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CW_LRB_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CW_LRB_DEL
      set @flagreturn = 0
   end



----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG


























--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE [dbo].[CW_RJZINOUTMXB](@ItemBM varchar(30) ,                        -----如果为0000则全部仓库
                                                                                            @Begin_YYYYMM   varchar(10) ,
                                                                                           @End_YYYYMM   varchar(10) 
                        
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @End_YYYYMMAddone  datetime,
        @MAXBILLDATE  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
	@VENDOR_CLIENT_ID  varchar(20),
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8),
        @WHERESTING   varchar(1800)

declare @BANKNAME  varchar(50)
declare @ClientNAME  varchar(50)
declare @BANKSTR  varchar(50)
declare @STRZhaiYao   varchar(300)      -------收款方式、收款去向
declare @Memo   varchar(300)      -------收款方式、收款去向


declare @ID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare  @BILLTYPE  INTEGER
declare  @DuiFangKeMu  varchar(50)
declare @BILLCODE  nvarchar(50)
declare @BILLDATE  datetime
declare @BILLTYPENAME  nvarchar(50)
declare @Begin_Date  varchar(10)
declare @Debit NUMERIC(20,10)
declare @Credit NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @EAMOUNTPREV NUMERIC(20,10)
---//==========
declare @BAMOUNT NUMERIC(20,10)
declare @MAXID  nvarchar(50)
declare @JHD  INT


                   set @now_date=(select   max(billDATE)   FROM CW_billflow)

		set @Begin_Date=substring(@Begin_YYYYMM,1,4)+'-'+substring(@Begin_YYYYMM,5,2)+'-01'

		update CW_BILLFLOW  set xuhao=ID  where xuhao is null   and  YYYYMMBILL=1
                      

                          SELECT    @WHERESTING  = '  AND     YYYYMM >='+char(39)+@Begin_YYYYMM+char(39)+' and  YYYYMM <='+char(39)+ @End_YYYYMM+char(39) 
                          SELECT    @BANKSTR  = '  AND     ItemBM ='+char(39)+@ItemBM+char(39)


  


Create Table #temptable1
      (ID  varchar(20) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
   YYYYMM  varchar(50)  NULL,
   xuhao  varchar(50)  NULL,
	[Debit] NUMERIC(20,10)  NULL ,
	[Credit] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
   zhaiyao  varchar(200)  NULL,
   ItemBM  varchar(30)  NULL
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   ID , BILLID,BILLTYPE,BILLCODE,BILLDATE,BILLTYPE,YYYYMM, xuhao, '
           SELECT  @SQLSTR = @SQLSTR+'Debit,Credit,EAMOUNT ,brief,duifangkemu as ItemBM '
           SELECT  @SQLSTR = @SQLSTR+'  from CW_billflow   where yyyymmbill in (0,1,2)    '  + @WHERESTING+@BANKSTR 
           SELECT  @SQLSTR = @SQLSTR+'  order by id '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(20) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
   JHD_1 int  NULL,
	[Debit] NUMERIC(20,10)  NULL ,
	[Credit] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
    zhaiyao nvarchar(300)  NULL,
    Memo nvarchar(300)  NULL,
    ItemBM  varchar(30)  NULL
		)


---------------------------------------------------
		select @JHD=JHD  from ItemInfo where ItemBM=@ItemBM

	          set @COUNTID='00000001'
	   if exists (Select  ID,BILLID,BILLTYPE, BILLCODE,BILLDATE,BILLTYPENAME,
                                                     isnull(Debit,0) as Debit ,  isnull(Credit,0) as Credit ,
                                                     isnull(EAMOUNT,0) as EAMOUNT   from  #temptable1        )
                 begin
	    declare INOUTMXBREP Cursor for Select  ID,BILLID,BILLTYPE , BILLCODE,BILLDATE,BILLTYPENAME,
                                                       isnull(Debit,0) as Debit ,   isnull(Credit,0) as Credit ,
                                                     isnull(EAMOUNT,0) as EAMOUNT ,ItemBM,zhaiyao  from  #temptable1         ORDER BY YYYYMM,BILLDATE,xuhao
	    Open INOUTMXBREP

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @Debit,@Credit,@EAMOUNT,@DuiFangKemu,@STRZhaiYao

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                        SELECT  @MAXID=ID  FROM CW_billflow  WHERE  ItemBM=@ItemBM  AND YYYYMM=@Begin_YYYYMM   AND YYYYMMBILL=0
                        IF @MAXID IS NULL
 			BEGIN
			SET  @BAMOUNT=0
			END
                        ELSE
			BEGIN
	                           SELECT @BAMOUNT=BAMOUNT   FROM   CW_billflow  WHERE ID=@MAXID
			END
                                                              
                          INSERT    INTO   #temptable2  (ID,BILLDATE, zhaiyao,EAMOUNT,JHD_1)
                                           VALUES  (@COUNTID ,@Begin_Date, '期初余额',@BAMOUNT,@JHD)
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID


                    INSERT    INTO   #temptable2  (ID,BILLID,BILLTYPE, BILLCODE,BILLDATE,ItemBM,
                                                               Debit,Credit,EAMOUNT,zhaiyao,Memo,JHD_1)
                                           VALUES  (@COUNTID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@DuiFangKeMu,
                                                               @Debit,@Credit,@EAMOUNT,@STRZhaiYao,@Memo,@JHD)

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @Debit,@Credit,@EAMOUNT,@DuiFangKemu,@STRZhaiYao
 

	    END           ------- INOUTMXBREP  WHILE

	    close INOUTMXBREP
	    deallocate INOUTMXBREP
        end     ------------  if exists
---------------------------
---------解决当前仓库本期间未发生业务的货品
--                  delete    #temptable1
            ELSE
            BEGIN

                        SELECT  @ID=ID  FROM CW_billflow  WHERE  ItemBM=@ItemBM  AND YYYYMM=@Begin_YYYYMM   AND YYYYMMBILL=0

	             	  SELECT    @ID=ID,@EAMOUNT=BAMOUNT    FROM  CW_billflow  WHERE    ID = @ID   


                 SELECT  @BANKNAME= FullName   FROM ItemInfo  WHERE ItemBM=@ItemBM
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME         )
                                           VALUES  (@COUNTID,@BANKNAME)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                                                              
                          INSERT    INTO   #temptable2  (ID ,billdate, zhaiyao,EAMOUNT)
                                           VALUES  (@COUNTID,@Begin_Date,'期初余额',@EAMOUNT)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期末结存',@EAMOUNT)

---------------------------
	END




--------------------------

 SELECT *  FROM #temptable2         ORDER BY ID

















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











--------------------------------------------------------------------
CREATE PROCEDURE [dbo].[CW_ShiSuanPHB](     @Begin_YYYYMM   varchar(10) ,
                                            @End_YYYYMM   varchar(10), 
                        				            @KeMuJiBie  int		

                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @End_YYYYMMAddone  datetime,
        @MAXBILLDATE  datetime,
        @temp_year   varchar(10), 
	@VENDOR_CLIENT_ID  varchar(20),
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8),
        @WHERESTING   varchar(1800)

declare @BANKNAME  varchar(50)
declare @ClientNAME  varchar(50)
declare @BANKSTR  varchar(50)
declare @STRZhaiYao   varchar(300)      -------收款方式、收款去向
declare @Memo   varchar(300)      -------收款方式、收款去向


declare @ID  varchar(50)
declare @BILLID  varchar(50)
declare @BILLTYPE  INTEGER
declare @NewYYYYMM  varchar(50)
declare @YYYYMM    varchar(50)
declare @BILLCODE  varchar(50)
declare @ItemBM    varchar(50)
declare @ItemBM00  varchar(50)
declare @BILLDATE  datetime
declare @Begin_Date  varchar(10)
declare @Debit NUMERIC(20,2)
declare @Credit NUMERIC(20,2)
declare @EAMOUNT NUMERIC(20,2)
declare @EAMOUNTPREV NUMERIC(20,2)
declare @KeMuLen  INT
declare @KeMuLenSTR  varchar(500)

declare @Step0 int
declare @Step1 int
declare @Step2 int
declare @Step3 int
declare @Step4 int
declare @Step5 int
declare @Step6 int
declare @Step7 int
declare @Step8 int
declare @Step9 int

---//==========
declare @BAMOUNT NUMERIC(20,2)
declare @MAXID  varchar(50)
  declare @bdebit_count numeric(20,6),
	  @bcredit_count numeric(20,6),
	  @debit_count numeric(20,6),
	  @credit_count numeric(20,6),
	  @edebit_count numeric(20,6),
	  @ecredit_count numeric(20,6),
          @ydebit_count numeric(20,6),
	  @ycredit_count numeric(20,6)




		set @Begin_Date=substring(@Begin_YYYYMM,1,4)+'-'+substring(@Begin_YYYYMM,5,2)+'-01'






	select @Step0=Step0,@Step1=Step1,@Step2=Step2,@Step3=Step3,@Step4=Step4,@Step5=Step5,@Step6=Step6,@Step7=Step7,
		@Step8=Step8,@Step9=Step9  FROM  ACCINFO  WHERE GUID='0001'



	IF @KeMuJiBie=1
	begin
		set @KeMuLen=@Step0
	end
	IF @KeMuJiBie=2
	begin
		set @KeMuLen=@Step0+@Step1
	end
	IF @KeMuJiBie=3
	begin
		set @KeMuLen=@Step0+@Step1+@Step2
	end
	IF @KeMuJiBie=4
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3
	end
	IF @KeMuJiBie=5
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4
	end
	IF @KeMuJiBie=6
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5
	end
	IF @KeMuJiBie=7
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6
	end
	IF @KeMuJiBie=8
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7
	end
	IF @KeMuJiBie=9
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7+@Step8
	end
	IF @KeMuJiBie=10
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7+@Step8+@Step9
	end


	SET @KeMuLenSTR	=' where  Len(I.ItemBM) <=  '+ Cast(@KeMuLen as Varchar(2))





----------------第二个会计期间新增会计科目问题

----------------关于年中新增会计科目，增加新增会计科目的月结记录

  create table #trytable (
    ItemBMBB    varchar(50)  NULL,
    ItemBM    varchar(50)  NULL,
    FullName    varchar(300)  NULL,
    debit  numeric(20,6) NULL,--本期借方
    credit numeric(20,6) NULL,--本期贷方
    ydebit numeric(20,6) NULL,--本年累计借方
    ycredit numeric(20,6) NULL,--本年累计贷方
    bdebit numeric(20,6) NULL,--期初借方
    bcredit numeric(20,6) NULL,--期初贷方
    edebit numeric(20,6) NULL,--期末借方
    ecredit numeric(20,6) NULL)--期末贷方
 



                          SELECT    @WHERESTING  = '  AND     YYYYMM >='+char(39)+@Begin_YYYYMM+char(39)+' and  YYYYMM <='+char(39)+ @End_YYYYMM+char(39) 

     
	        SELECT @SQLSTR = ' INSERT #trytable  '
		SELECT @SQLSTR=@SQLSTR+'	 select I.ITemBM as ItemBMBB ,I.ITemBM, I.FullName,  isnull(E.Debit,0) as Debit,isnull(E.Credit,0) as Credit,'
		SELECT @SQLSTR=@SQLSTR+'	 			   case when isnull(M.Debit,0)>isnull(M.Credit,0) then isnull(M.Debit,0)-isnull(M.Credit,0)'
		SELECT @SQLSTR=@SQLSTR+'	 			   else 0 '
		SELECT @SQLSTR=@SQLSTR+'	 			   end  as  YDebit,'
		SELECT @SQLSTR=@SQLSTR+'	 			   case when isnull(M.Credit,0)>isnull(M.Debit,0) then isnull(M.Credit,0)-isnull(M.Debit,0)'
		SELECT @SQLSTR=@SQLSTR+'	 			   else 0 '
		SELECT @SQLSTR=@SQLSTR+'	 			   end  as  YCredit,'
		SELECT @SQLSTR=@SQLSTR+'	 			   isnull(N.Bamount,0) as BDebit,isnull(X.Bamount,0) as BCredit,'
		SELECT @SQLSTR=@SQLSTR+'	 			   case when I.JHD=1 then  isnull(BB.Bamount,0)+isnull(E.Debit,0)-isnull(E.Credit,0)'
		SELECT @SQLSTR=@SQLSTR+'	 			   else 0 '
		SELECT @SQLSTR=@SQLSTR+'	 			   end  as  EDebit,'
		SELECT @SQLSTR=@SQLSTR+'	 			   case when I.JHD=-1 then  isnull(BB.Bamount,0)-isnull(E.Debit,0)+isnull(E.Credit,0)'
		SELECT @SQLSTR=@SQLSTR+'	 			   else 0 '
		SELECT @SQLSTR=@SQLSTR+'	 			   end  as  ECredit	'
		SELECT @SQLSTR=@SQLSTR+'	 	        From  ItemInfo  '
		SELECT @SQLSTR=@SQLSTR+'	 	  AS I '
		SELECT @SQLSTR=@SQLSTR+'	 	 left outer join '
		SELECT @SQLSTR=@SQLSTR+'	 	 (select ITemBM,isnull(sum(Debit),0) as Debit ,isnull(sum(Credit),0) as Credit from  CW_BILLFLOW where YYYYMMBILL=1 '+@WHERESTING
		SELECT @SQLSTR=@SQLSTR+'	 		Group BY ITemBM 	'
		SELECT @SQLSTR=@SQLSTR+'	 	 ) as E ON E.ITemBM=I.ITemBM '
		SELECT @SQLSTR=@SQLSTR+'	 	 left outer join '
		SELECT @SQLSTR=@SQLSTR+'	 	 (select ITemBM,isnull(Debit,0) as Debit,isnull(Credit,0) as Credit  from  CW_BILLFLOW where   YYYYMMBILL=2  and   YYYYMM = '+char(39)+ @End_YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+'	 	 ) as M ON M.ITemBM=I.ITemBM '
		SELECT @SQLSTR=@SQLSTR+'	 	 left outer join '
		SELECT @SQLSTR=@SQLSTR+'	 	 (select ITemBM,isnull(Bamount,0) as Bamount from  CW_BILLFLOW where JHD=1  and YYYYMMBILL=0   AND   YYYYMM ='+char(39)+@Begin_YYYYMM+char(39)
		SELECT @SQLSTR=@SQLSTR+'	 	 ) as N ON N.ITemBM=I.ITemBM '
		SELECT @SQLSTR=@SQLSTR+'	 	 left outer join '
		SELECT @SQLSTR=@SQLSTR+'	 	 (select ITemBM,isnull(Bamount,0) as Bamount from  CW_BILLFLOW where JHD=-1  and YYYYMMBILL=0   AND     YYYYMM ='+char(39)+@Begin_YYYYMM+char(39)
		SELECT @SQLSTR=@SQLSTR+'	 	 ) as X ON X.ITemBM=I.ITemBM '
		SELECT @SQLSTR=@SQLSTR+'	 	 left outer join '
		SELECT @SQLSTR=@SQLSTR+'	 	 (select ITemBM,isnull(Bamount,0) as Bamount from  CW_BILLFLOW where  YYYYMMBILL=0  and   YYYYMM ='+char(39)+@Begin_YYYYMM+char(39)
		SELECT @SQLSTR=@SQLSTR+'	 	 ) as BB ON BB.ITemBM=I.ITemBM '
---		SELECT @SQLSTR=@SQLSTR+'	 	where  len(I.ItemBM)=4 '
		SELECT @SQLSTR=@SQLSTR+@KeMuLenSTR

	            EXEC( @SQLSTR)


  update #trytable set ecredit = -edebit	  where edebit<0

  update #trytable set edebit = 0	  where edebit<0


  update #trytable set edebit = -ecredit	  where ecredit<0

  update #trytable set ecredit = 0	  where ecredit<0
--------------------

  update #trytable set Bcredit = -Bdebit	  where Bdebit<0

  update #trytable set Bdebit = 0	  where Bdebit<0


  update #trytable set Bdebit = -Bcredit	  where Bcredit<0

  update #trytable set Bcredit = 0	  where Bcredit<0
------------------------
  select @bdebit_count = sum(bdebit),
         @bcredit_count = sum(bcredit),
         @debit_count = sum(debit),
         @credit_count = sum(credit),
         @edebit_count = sum(edebit),
         @ecredit_count = sum(ecredit),
         @ydebit_count = sum(ydebit),
         @ycredit_count = sum(ycredit)
  from #trytable where len(ItemBM)=4 


  insert into #trytable (ItemBMBB,FullName, bdebit, bcredit, debit, credit, edebit, ecredit, ydebit, ycredit)
                         values('99999999999999999999',
                               '          合  计 ',@bdebit_count,@bcredit_count,@debit_count,@credit_count,
                                                @edebit_count,@ecredit_count,@ydebit_count,@ycredit_count)  

  delete from #trytable where     (bdebit=0 or bdebit is null)
                              and (bcredit=0 or bcredit is null)
                              and (debit=0 or debit is null)
                              and (credit=0 or credit is null)
                              and (edebit=0 or edebit is null)
                              and (ecredit=0 or ecredit is null)  

  select ItemBM,FullName, bdebit, bcredit, debit, credit, edebit, ecredit, ydebit, ycredit   
	  from #trytable  
	  order by ItemBMBB 
---  drop table #trytable

---	select *  from #trytable where  ItemBM='1001'












----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG


















CREATE                PROCEDURE CW_UpdateCW_INITBALAtotal
AS
  set nocount on

  DECLARE @Debit T_DOUBLE
  DECLARE @Credit T_DOUBLE
  DECLARE @Balance T_DOUBLE
  DECLARE @STEP0 SMALLINT


  create table #CW_INITBALA99 (ItemBM varchar(32),
                             fullname varchar(400),
                             step0 varchar(1),
                             moneyid integer  NULL ,  
                             rate numeric(38,8) ,      
                             rawdebit numeric(38,8) ,    ----年初借方       
                             rawcredit numeric(38,8) ,   ----年初贷方         
                             rawbalance numeric(38,8) ,   
                             debit numeric(38,8) ,         
                             credit numeric(38,8) ,         
                             balance numeric(38,8) ,         
                             balance_jie numeric(38,8) ,       ----期初借方  
                             balance_Dai numeric(38,8) ,       ----期初贷方    
                             plhavedone numeric(38,8),        
                             refreshflag varchar(1), 
			     [DCFlag] int  NULL )


  create table #CW_INITBALA_all ( ItemBM varchar(32),
                             fullname varchar(400),
                             step0 varchar(1),
                             moneyid integer  NULL ,  
                             rate numeric(38,8) NOT NULL ,      
                             rawdebit numeric(38,8) ,    ----年初借方       
                             rawcredit numeric(38,8) ,   ----年初贷方         
                             rawbalance numeric(38,8) NOT NULL ,   
                             debit numeric(38,8) NOT NULL ,         
                             credit numeric(38,8) NOT NULL ,         
                             balance numeric(38,8) NOT NULL ,         
                             balance_jie numeric(38,8) ,       ----期初借方  
                             balance_Dai numeric(38,8) ,       ----期初贷方    
                             plhavedone numeric(38,8) NOT NULL ,       
                             refreshflag varchar(1), 
			     [DCFlag] int  NULL )



  -- 求综合本位币的数据
-----现在只求一种货币的数据
/*  UPDATE CW_INITBALA
  SET
    Debit=Src.Debit,Credit=Src.Credit,Balance=Src.Balance,PLHaveDone=Src.PLHaveDone
    
  FROM(SELECT ItemBM,SUM(Debit) Debit,SUM(Credit) Credit,SUM(Balance) Balance,
    SUM(PLHaveDone) PLHaveDone
    FROM CW_INITBALA 
    WHERE MoneyID<>99 GROUP BY ItemBM
  ) Src
  WHERE CW_INITBALA.MoneyID=99 AND CW_INITBALA.ItemBM=Src.ItemBM
*/

-------在一种货币的情况下不需要以上指令

    --选入CW_INITBALA表中99数据到临时表
/*    insert into #CW_INITBALA_all select b.ItemBM,b.fullname,'F' as step0,  a.* from CW_INITBALA  a, ItemInfo b 
             where a.ItemBM = b.ItemBM and a.moneyid = 99
*/
    insert into #CW_INITBALA_all select b.ItemBM,b.fullname,'F' as step0,  a.moneyid,	a.rate,	a.rawdebit,	a.rawcredit,	a.rawbalance,	a.debit,	a.credit,a.balance, 0  as balance_jie, 0  as balance_Dai, a.plhavedone,	a.refreshflag,	a.DCFlag from CW_INITBALA  a, ItemInfo b 
             where a.ItemBM = b.ItemBM 



    update #CW_INITBALA_all set rawbalance = - a.rawbalance ,
                         balance = -a.balance  
          from #CW_INITBALA_all a , ItemInfo b 
          where a.ItemBM = b.ItemBM and b.dcflag <>1    -- 为了能向上级求合统计 将balance改为科目的方向无关  
   
    insert into #CW_INITBALA99 select * from #CW_INITBALA_all
    --插入非底层的科目
    insert into #CW_INITBALA99 (ItemBM,fullname,moneyid) 
       select a.ItemBM ,a.fullname, 99 as moneyid
           from ItemInfo a 
                where a.detailflag <> 1
    
/*    update #CW_INITBALA99 set rate = ( select isnull(max(rate),1)   from #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%' and moneyid = a.moneyid ) ,
                       rawdebit = ( select isnull(sum(rawdebit),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%' and moneyid = a.moneyid ) ,

                       rawcredit = ( select isnull(sum(rawcredit),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%' and moneyid = a.moneyid ) ,
               
                       rawbalance = ( select isnull(sum(rawbalance),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%' and moneyid = a.moneyid ) ,


                       debit = ( select isnull(sum(debit),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%' and moneyid = a.moneyid ) ,

                       credit = ( select isnull(sum(credit),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%' and moneyid = a.moneyid ) ,

                       balance = ( select isnull(sum(balance),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%' and moneyid = a.moneyid ) ,
 

                       plhavedone = ( select isnull(sum(plhavedone),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%' and moneyid = a.moneyid ) 
    from #CW_INITBALA99 a , ItemInfo b 
    where a.ItemBM = b.ItemBM and b.detailflag <> 1 

*/
    update #CW_INITBALA99 set rate = ( select isnull(max(rate),1)   from #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%') ,
                       rawdebit = ( select isnull(sum(rawdebit),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%') ,

                       rawcredit = ( select isnull(sum(rawcredit),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%') ,
               
                       rawbalance = ( select isnull(sum(rawbalance),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%' ) ,


                       debit = ( select isnull(sum(debit),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%') ,

                       credit = ( select isnull(sum(credit),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%') ,

                       balance = ( select isnull(sum(balance),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%') ,
 

                       plhavedone = ( select isnull(sum(plhavedone),0) from  #CW_INITBALA_all 
                                    where ItemBM like a.ItemBM +'%') 
    from #CW_INITBALA99 a , ItemInfo b 
    where a.ItemBM = b.ItemBM and b.detailflag <> 1 


   
    --处理CW_INITBALA 的余额方向
    update #CW_INITBALA99 set rawbalance = - a.rawbalance , 
                        balance = -a.balance 
           from #CW_INITBALA99 a , ItemInfo b 
           where a.ItemBM = b.ItemBM and b.dcflag <>1 --and b.detailflag <> 1   

-----------和上边的处理余额方向相反，相对应     

---    FieldByName('YearBalance').AsFloat=FieldByName('Balance').AsFloat-FieldByName('Debit').AsFloat+FieldByName('credit').AsFloat;

-------处理年初余额

    update #CW_INITBALA99 set Rawbalance = Balance-Debit+credit from #CW_INITBALA99 

--                             rawdebit numeric(38,8) ,    ----年初借方       
--                             rawcredit numeric(38,8) ,   ----年初贷方         

    --处理#CW_INITBALA99 的期初借方、贷方，以及处理年初借方与贷方
    update #CW_INITBALA99 set balance_Dai = a.balance,rawcredit=a.Rawbalance 
           from #CW_INITBALA99 a , ItemInfo b 
           where a.ItemBM = b.ItemBM and b.dcflag <>1 --and b.detailflag <> 1   

    update #CW_INITBALA99 set balance_Jie = a.balance , rawdebit=a.Rawbalance
           from #CW_INITBALA99 a , ItemInfo b 
           where a.ItemBM = b.ItemBM and b.dcflag =1 --and b.detailflag <> 1   

-----------和上边的处理余额方向相反，相对应     

  
 SELECT @STEP0=STEP0 FROM ACCINFO
/*   IF (@STEP0=4)
    SELECT @Debit=sum(Debit),@Credit=sum(Credit),@balance = Sum(Case When dcflag =1 then Balance else -Balance end ) 
    FROM #CW_INITBALA99 a, ItemInfo s  WHERE a.MoneyID=99 and a.ItemBM = s.ItemBM 
    AND   a.ItemBM Like '____' 
  ELSE
   SELECT @Debit=sum(Debit),@Credit=sum(Credit),@balance = Sum(Case When dcflag =1 then Balance else -Balance end ) 
    FROM #CW_INITBALA99 a, ItemInfo s  WHERE a.MoneyID=99 and a.ItemBM = s.ItemBM 
    AND  a.ItemBM Like '___' 
*/

-------以上不知道是什么意思，暂时屏蔽掉

/*  INSERT INTO #CW_INITBALA99
    (ItemBM,ItemBM,fullname,MoneyID,
    Debit,Credit,Balance)
  VALUES(-99999,'99999999999999','合    计',-9999,
    ROUND(@Debit,2),ROUND(@Credit,2),@Balance)
*/
-------以上不知道是何用途，暂时屏蔽掉
-------step0  一级科目的标志

  update #CW_INITBALA99 set  step0 = 'T' where len(ItemBM) = @STEP0
  select ItemBM, fullname,step0,moneyid, rate, rawdebit, rawcredit, rawbalance, debit, credit,
		 balance, balance_jie, balance_dai, plhavedone, refreshflag
  from #CW_INITBALA99 order by ItemBM
  drop table #CW_INITBALA_all
  drop table #CW_INITBALA99













----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













CREATE PROCEDURE [dbo].[CW_XJLLBMB_CRAET_CW_XJLLB](@BILLID varchar(8),                        -----如果为0000则全部仓库
						           @YearMonth   varchar(10),  
								   @RETURNSTRING    varchar(60)    output      ---单据编号   
                                                      )    --APSOFTENCRYPTION       WITH ENCRYPTION
as
declare @CODE00   [varchar] (25)   
declare @NewBILLID   varchar (50)   
declare @SFLAG  INTEGER
declare @BILLTYPE   INTEGER
declare @NewBILLDATE DATEtime


-------利润表的模板是唯一的，所以不需要传递参数  @BILLID

-----	select @BILLID = BILLID from STORECW_XJLLBMBM


	EXEC CW_BILL_XuHao_ChongPai 'STORECW_XJLLBMBD',@BILLID

	delete STORECW_XJLLBM  WHERE YearMonth=@YearMonth

----------如果存在就删除
	
	INSERT INTO STORECW_XJLLBM
	SELECT *  FROM  STORECW_XJLLBMBM WHERE BILLID=@BILLID

	INSERT INTO STORECW_XJLLBD
	SELECT *  FROM  STORECW_XJLLBMBD WHERE BILLID=@BILLID


	UPDATE STORECW_XJLLBM SET CODE=Substring(@YearMonth,1,4)+'年'+Substring(@YearMonth,5,2)+'月',
				YearMonth=@YearMonth,BillDate=getdate() WHERE BILLID=@BILLID


	UPDATE STORECW_XJLLBM SET BILLID=@YearMonth+BILLID   WHERE BILLID=@BILLID 
	UPDATE STORECW_XJLLBD SET ItemNO=@YearMonth+ItemNO   WHERE BILLID=@YearMonth+@BILLID


	SET @NewBILLID=@YearMonth+@BILLID
	declare @RETURNSTRING00  varchar(60) 
	declare @flagreturn00 int    ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
	exec CW_XJLLB_JiSuan  @NewBILLID,@RETURNSTRING00 ,@flagreturn00 output  

--	select @flagreturn




	SET @RETURNSTRING ='成功生成报表，表号为'+ @YearMonth

















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[CW_XJLLB_JiSuan]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare  @INF_COSTINGTYPEID  INT
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @CLIENTID varchar(10)                   --单句会计年月     
declare @ITEMNO varchar(15)               --明细存货编号
declare @XuHao varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @MM   INT          --明细存货编号
declare @A   varchar(500)               --明细存货编号
declare @B   varchar(500)               --明细存货编号
declare @C   varchar(500)               --明细存货编号
declare @D   varchar(500)               --明细存货编号
declare @E   varchar(500)               --明细存货编号
declare @YearMonth  varchar(6)
declare @BILLTYPE   INTEGER
declare @SFLAG   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @C_GongShi   varchar(500)               --明细存货编号
declare @D_GongShi   varchar(500)               --明细存货编号
declare @E_GongShi   varchar(500)               --明细存货编号
declare @C_Value   varchar(500)               --明细存货编号
declare @D_Value   varchar(500)               --明细存货编号
declare @E_Value   varchar(500)               --明细存货编号


                                              SET @RETURNSTRING='   '


	set @BILLID   = ltrim(rtrim(@BILLID))
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CW_XJLLB_DEL   --事物开始

     set @YearMonth =   (select YearMonth  from STORECW_XJLLBM where rtrim(BILLID) = @BILLID)


    declare SM_Consign_CW_XJLLB_DEL Cursor for Select ITEMNO,XuHao,A,B ,C,D,E   from STORECW_XJLLBD where rtrim(BILLID) = @BILLID  Order BY ITEMNO

    Open SM_Consign_CW_XJLLB_DEL

    fetch SM_Consign_CW_XJLLB_DEL into @ITEMNO,@XuHao,@A,@B,@C,@D,@E

    while @@fetch_status = 0            ----开始
    begin

--------------分别取C列与D列公式

		
		select @C_GongShi=C From STORECW_XJLLBMBD where XuHao=@XuHao

		select @D_GongShi=D From STORECW_XJLLBMBD where XuHao=@XuHao




--     select PATINDEX('%[0-9]%', '234GHJ')
--     select PATINDEX('%[A-Fa-f]%', '234GHJ')
-----------------需要判断是否需要计算，是否是公式

			IF	CHARINDEX('ACCT',@C_GongShi)>0  OR 
				(PATINDEX('%[A-Na-n]%', @C_GongShi) >0 and PATINDEX('%[0-9]%', @C_GongShi) >0)
			begin
		                exec [dbo].[CW_GongShiZhiXing] 'STORECW_XJLLBD',@BILLID,@C_GongShi,@YearMonth, @C_Value output
			end
			else
			begin
		                SET @C_Value=@C_GongShi
			end
	
----------------------------------------------------			
			IF	CHARINDEX('ACCT',@D_GongShi)>0  OR 
				(PATINDEX('%[A-Na-n]%', @D_GongShi) >0 and PATINDEX('%[0-9]%', @D_GongShi) >0)
			begin
		                exec [dbo].[CW_GongShiZhiXing] 'STORECW_XJLLBD',@BILLID,@D_GongShi,@YearMonth, @D_Value output
			end
			else
			begin
		                SET @D_Value=@D_GongShi
			end
------------------------------------------------------	

		update STORECW_XJLLBD SET C=@C_Value,D=@D_Value   where ItemNO=@ITEMNO

		update STORECW_XJLLBD SET C=NULL    where C='0.00'
		update STORECW_XJLLBD SET D=NULL    where D='0.00'


-----CREATE PROCEDURE [dbo].[CW_GongShiZhiXing] (@TableName  varchar(50),@GongShiStr  varchar(2000),@YearMonth  varchar(10),@ReturnSTR varchar(100)  output)


--------------------
    fetch SM_Consign_CW_XJLLB_DEL into @ITEMNO,@XuHao,@A,@B,@C,@D,@E

    END           ------- SM_Consign_CW_XJLLB_DEL  WHILE

    close SM_Consign_CW_XJLLB_DEL
    deallocate SM_Consign_CW_XJLLB_DEL


------------------------------------以上是删除全部单据明细

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CW_XJLLB_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CW_XJLLB_DEL
      set @flagreturn = 0
   end




----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG








CREATE PROCEDURE [dbo].[CW_XianJinLLFP](@BILLID varchar(20),                        -----如果为0000则全部仓库
					   @RETURNSTRING    varchar(500)    output ,     ---单据编号   
			                   @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） 
                                                      )    --APSOFTENCRYPTION       WITH ENCRYPTION
as
declare @CODE00   [varchar] (25)   
declare @CashDebit NUMERIC(20,2)
declare @CashCredit NUMERIC(20,2)
declare @SumDebit NUMERIC(20,2)
declare @SumCredit NUMERIC(20,2)
declare @STR00   [varchar] (100)   
declare @STR11   [varchar] (100)   
declare @STR22   [varchar] (100)   

	select @SumDebit=Isnull(sum(Debit),0),@SumCredit=Isnull(sum(Credit),0)    from CW_CashItemTMP where BILLID=@BILLID

	select @CashDebit=Isnull(CashDebit,0),@CashCredit=Isnull(CashCredit,0)    from CW_PingZhengM where BILLID=@BILLID
	
	set @flagreturn=0

        set @STR00='凭证中现金流量类科目借方、贷方差额为：'+ cast((@CashDebit-@CashCredit) as Varchar(20))
        set @STR11='而现金流量金额分配中流入、流出差额为：'+ cast((@SumDebit-@SumCredit) as Varchar(20))
        set @STR22='两者不相等！分配不正确！'

	IF @SumDebit=@CashDebit and @SumCredit=@CashCredit
	BEGIN
	delete  CW_CashItem where BILLID=@BILLID

	INSERT INTO CW_CashItem
	SELECT *  FROM  CW_CashItemTMP WHERE BILLID=@BILLID and (ISNULL(Debit,0)<>0 OR ISNULL(Credit,0)<>0)

	update CW_PingZhengM  set CashFlag=1  where BILLID=@BILLID
	set @flagreturn=1

	SET @RETURNSTRING ='成功分配现金流量'
	END
        ELSE
	BEGIN
	set @flagreturn=0
	SET @RETURNSTRING =@STR00+@STR11+@STR22
	END








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













CREATE PROCEDURE [dbo].[CW_ZCFZBMB_CRAET_CW_ZCFZB](@BILLID varchar(8),                        -----如果为0000则全部仓库
						           @YearMonth   varchar(10),  
								   @RETURNSTRING    varchar(60)    output      ---单据编号   
                                                      )    --APSOFTENCRYPTION       WITH ENCRYPTION
as
declare @CODE00   [varchar] (25)   
declare @NewBILLID   varchar (50)   
declare @SFLAG  INTEGER
declare @BILLTYPE   INTEGER
declare @NewBILLDATE DATEtime


-------利润表的模板是唯一的，所以不需要传递参数  @BILLID

-----	select @BILLID = BILLID from STORECW_ZCFZBMBM


	EXEC CW_BILL_XuHao_ChongPai 'STORECW_ZCFZBMBD',@BILLID

	delete STORECW_ZCFZBM  WHERE YearMonth=@YearMonth

----------如果存在就删除
	
	INSERT INTO STORECW_ZCFZBM
	SELECT *  FROM  STORECW_ZCFZBMBM WHERE BILLID=@BILLID

	INSERT INTO STORECW_ZCFZBD
	SELECT *  FROM  STORECW_ZCFZBMBD WHERE BILLID=@BILLID


	UPDATE STORECW_ZCFZBM SET CODE=Substring(@YearMonth,1,4)+'年'+Substring(@YearMonth,5,2)+'月',
				YearMonth=@YearMonth,BillDate=getdate() WHERE BILLID=@BILLID


	UPDATE STORECW_ZCFZBM SET BILLID=@YearMonth+BILLID   WHERE BILLID=@BILLID 
	UPDATE STORECW_ZCFZBD SET ItemNO=@YearMonth+ItemNO   WHERE BILLID=@YearMonth+@BILLID


	SET @NewBILLID=@YearMonth+@BILLID
	declare @RETURNSTRING00  varchar(60) 
	declare @flagreturn00 int    ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
	exec CW_ZCFZB_JiSuan  @NewBILLID,@RETURNSTRING00 ,@flagreturn00 output  

--	select @flagreturn




	SET @RETURNSTRING ='成功生成报表，表号为'+ @YearMonth

















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[CW_ZCFZB_JiSuan]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare  @INF_COSTINGTYPEID  INT
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @CLIENTID varchar(10)                   --单句会计年月     
declare @ITEMNO varchar(15)               --明细存货编号
declare @XuHao varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @MM   INT          --明细存货编号
declare @A   varchar(500)               --明细存货编号
declare @B   varchar(500)               --明细存货编号
declare @C   varchar(500)               --明细存货编号
declare @D   varchar(500)               --明细存货编号
declare @E   varchar(500)               --明细存货编号
declare @F   varchar(500)               --明细存货编号
declare @G   varchar(500)               --明细存货编号
declare @H   varchar(500)               --明细存货编号
declare @YearMonth  varchar(6)
declare @BILLTYPE   INTEGER
declare @SFLAG   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @C_GongShi   varchar(500)               --明细存货编号
declare @D_GongShi   varchar(500)               --明细存货编号
declare @G_GongShi   varchar(500)               --明细存货编号
declare @H_GongShi   varchar(500)               --明细存货编号
declare @C_Value   varchar(500)               --明细存货编号
declare @D_Value   varchar(500)               --明细存货编号
declare @G_Value   varchar(500)               --明细存货编号
declare @H_Value   varchar(500)               --明细存货编号


                                              SET @RETURNSTRING='   '


	set @BILLID   = ltrim(rtrim(@BILLID))
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CW_ZCFZB_DEL   --事物开始

     set @YearMonth =   (select YearMonth  from STORECW_ZCFZBM where rtrim(BILLID) = @BILLID)


    declare SM_Consign_CW_ZCFZB_DEL Cursor for Select ITEMNO,XuHao,A,B ,C,D,E,F,G,H   from STORECW_ZCFZBD where rtrim(BILLID) = @BILLID  Order BY ITEMNO

    Open SM_Consign_CW_ZCFZB_DEL

    fetch SM_Consign_CW_ZCFZB_DEL into @ITEMNO,@XuHao,@A,@B,@C,@D,@E,@F,@G,@H

    while @@fetch_status = 0            ----开始
    begin

--------------分别取C列与D列公式

		
		select @C_GongShi=C From STORECW_ZCFZBMBD where XuHao=@XuHao

		select @D_GongShi=D From STORECW_ZCFZBMBD where XuHao=@XuHao

		select @G_GongShi=G From STORECW_ZCFZBMBD where XuHao=@XuHao

		select @H_GongShi=H From STORECW_ZCFZBMBD where XuHao=@XuHao

                           print  @xuhao



--     select PATINDEX('%[0-9]%', '234GHJ')
--     select PATINDEX('%[A-Fa-f]%', '234GHJ')
-----------------需要判断是否需要计算，是否是公式

			IF	CHARINDEX('ACCT',@C_GongShi)>0  OR 
				(PATINDEX('%[A-Na-n]%', @C_GongShi) >0 and PATINDEX('%[0-9]%', @C_GongShi) >0)
			begin
		                exec [dbo].[CW_GongShiZhiXing] 'STORECW_ZCFZBD',@BILLID,@C_GongShi,@YearMonth, @C_Value output
			end
			else
			begin
		                SET @C_Value=@C_GongShi
			end
	
----------------------------------------------------			
			IF	CHARINDEX('ACCT',@D_GongShi)>0  OR 
				(PATINDEX('%[A-Na-n]%', @D_GongShi) >0 and PATINDEX('%[0-9]%', @D_GongShi) >0)
			begin
		                exec [dbo].[CW_GongShiZhiXing] 'STORECW_ZCFZBD',@BILLID,@D_GongShi,@YearMonth, @D_Value output
			end
			else
			begin
		                SET @D_Value=@D_GongShi
			end
------------------------------------------------------	
			IF	CHARINDEX('ACCT',@G_GongShi)>0  OR 
				(PATINDEX('%[A-Na-n]%', @G_GongShi) >0 and PATINDEX('%[0-9]%', @G_GongShi) >0)
			begin
		                exec [dbo].[CW_GongShiZhiXing] 'STORECW_ZCFZBD',@BILLID,@G_GongShi,@YearMonth, @G_Value output
			end
			else
			begin
		                SET @G_Value=@G_GongShi
			end
-------------------------------------------------------	
			IF	CHARINDEX('ACCT',@H_GongShi)>0  OR 
				(PATINDEX('%[A-Na-n]%', @H_GongShi) >0 and PATINDEX('%[0-9]%', @H_GongShi) >0)
			begin
		                exec [dbo].[CW_GongShiZhiXing] 'STORECW_ZCFZBD',@BILLID,@H_GongShi,@YearMonth, @H_Value output
			end
			else
			begin
		                SET @H_Value=@H_GongShi
			end
-------------------------------------------------------	


		update STORECW_ZCFZBD SET C=@C_Value,D=@D_Value,G=@G_Value,H=@H_Value    where ItemNO=@ITEMNO

		update STORECW_ZCFZBD SET C=NULL    where C='0.00'
		update STORECW_ZCFZBD SET D=NULL    where D='0.00'
		update STORECW_ZCFZBD SET G=NULL    where G='0.00'
		update STORECW_ZCFZBD SET H=NULL    where H='0.00'


-----CREATE PROCEDURE [dbo].[CW_GongShiZhiXing] (@TableName  varchar(50),@GongShiStr  varchar(2000),@YearMonth  varchar(10),@ReturnSTR varchar(100)  output)


--------------------
    fetch SM_Consign_CW_ZCFZB_DEL into @ITEMNO,@XuHao,@A,@B,@C,@D,@E,@F,@G,@H

    END           ------- SM_Consign_CW_ZCFZB_DEL  WHILE

    close SM_Consign_CW_ZCFZB_DEL
    deallocate SM_Consign_CW_ZCFZB_DEL


------------------------------------以上是删除全部单据明细

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CW_ZCFZB_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CW_ZCFZB_DEL
      set @flagreturn = 0
   end




----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG
























--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE [dbo].[CW_ZongFenLeiZhang](@BeginItemBM varchar(30) ,                        -----如果为0000则全部仓库
					    @ENDItemBM varchar(30) ,                        -----如果为0000则全部仓库
                                                                                            @Begin_YYYYMM   varchar(10) ,
                                                                                           @End_YYYYMM   varchar(10) ,
				            @KeMuJiBie  int		
                        
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @End_YYYYMMAddone  datetime,
        @MAXBILLDATE  datetime,
        @temp_year   varchar(10), 
	@VENDOR_CLIENT_ID  varchar(20),
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8),
        @WHERESTING   varchar(1800)

declare @BANKNAME  varchar(50)
declare @ClientNAME  varchar(50)
declare @BANKSTR  varchar(500)
declare @KeMuLenSTR  varchar(500)

declare @STRZhaiYao   varchar(300)      -------收款方式、收款去向
declare @Memo   varchar(300)      -------收款方式、收款去向


declare @ID  varchar(50)
declare @BILLID  varchar(50)
declare @BILLTYPE  INTEGER
declare @NewYYYYMM  varchar(50)
declare @YYYYMM    varchar(50)
declare @BILLCODE  varchar(50)
declare @ItemBM    varchar(50)
declare @ItemBM00  varchar(50)
declare @BILLDATE  datetime
declare @Begin_Date  varchar(10)
declare @Debit NUMERIC(20,2)
declare @Credit NUMERIC(20,2)
declare @EAMOUNT NUMERIC(20,2)
declare @EAMOUNTPREV NUMERIC(20,2)
---//==========
declare @BAMOUNT NUMERIC(20,2)
declare @MAXID  varchar(50)
declare @JHD  INT
declare @KeMuLen  INT

declare @Step0 int
declare @Step1 int
declare @Step2 int
declare @Step3 int
declare @Step4 int
declare @Step5 int
declare @Step6 int
declare @Step7 int
declare @Step8 int
declare @Step9 int





		set @Begin_Date=substring(@Begin_YYYYMM,1,4)+'-'+substring(@Begin_YYYYMM,5,2)+'-01'

                       

                          SELECT    @WHERESTING  = '  AND     YYYYMM >='+char(39)+@Begin_YYYYMM+char(39)+' and  YYYYMM <='+char(39)+ @End_YYYYMM+char(39) 
                          SELECT    @BANKSTR  = '  AND     ItemBM >='+char(39)+@BeginItemBM+char(39)+'  AND     ItemBM <='+char(39)+@ENDItemBM+char(39)



	select @Step0=Step0,@Step1=Step1,@Step2=Step2,@Step3=Step3,@Step4=Step4,@Step5=Step5,@Step6=Step6,@Step7=Step7,
		@Step8=Step8,@Step9=Step9  FROM  ACCINFO  WHERE GUID='0001'



	IF @KeMuJiBie=1
	begin
		set @KeMuLen=@Step0
	end
	IF @KeMuJiBie=2
	begin
		set @KeMuLen=@Step0+@Step1
	end
	IF @KeMuJiBie=3
	begin
		set @KeMuLen=@Step0+@Step1+@Step2
	end
	IF @KeMuJiBie=4
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3
	end
	IF @KeMuJiBie=5
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4
	end
	IF @KeMuJiBie=6
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5
	end
	IF @KeMuJiBie=7
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6
	end
	IF @KeMuJiBie=8
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7
	end
	IF @KeMuJiBie=9
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7+@Step8
	end
	IF @KeMuJiBie=10
	begin
		set @KeMuLen=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7+@Step8+@Step9
	end


	SET @KeMuLenSTR	=' AND Len(ItemBM) <=  '+ Cast(@KeMuLen as Varchar(2))





--@KeMuLen


     

Create Table #temptable1
      (ID  varchar(20) primary key,
   BILLID  varchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  varchar(50)  NULL,
   BILLDATE  datetime  NULL,
	[Debit] NUMERIC(20,2)  NULL ,
	[Credit] NUMERIC(20,2)  NULL ,
	[EAMOUNT]NUMERIC(20,2)  NULL ,
   zhaiyao  varchar(200)  NULL,
   ItemBM  varchar(200)  NULL,
   YYYYMM  varchar(200)  NULL

		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   ID , BILLID,BILLTYPE,BILLCODE,BILLDATE, '
           SELECT  @SQLSTR = @SQLSTR+' Debit,Credit,EAMOUNT ,brief,ItemBM,YYYYMM '
           SELECT  @SQLSTR = @SQLSTR+'  from CW_billflow   where yyyymmbill in (0,2)    '  + @WHERESTING+@BANKSTR +@KeMuLenSTR	
           SELECT  @SQLSTR = @SQLSTR+'  order by ItemBM,id '  
	print @SQLSTR


            EXEC( @SQLSTR)

Create Table #temptable2
      (ID  varchar(20) primary key,
   BILLID  varchar(50)  NULL,
   BILLTYPE  INTEGER,
   ItemBM  varchar(30)  NULL,
   JHD int  NULL,
   BILLCODE  varchar(100)  NULL,
   BILLDATE  datetime  NULL,
	[Debit] NUMERIC(20,2)  NULL ,
	[Credit] NUMERIC(20,2)  NULL ,
	[EAMOUNT]NUMERIC(20,2)  NULL ,
    zhaiyao varchar(300)  NULL,
    Memo    varchar(300)  NULL,
    NEWYYYYMM  varchar(300)  NULL
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	    declare INOUTMXBREP Cursor for Select  ID,BILLID,BILLTYPE , BILLCODE,BILLDATE,YYYYMM,
                                                       isnull(Debit,0) as Debit ,   isnull(Credit,0) as Credit ,
                                                     isnull(EAMOUNT,0) as EAMOUNT ,zhaiyao,ItemBM  from  #temptable1 
						     order by ItemBM,YYYYMM,id 
	    Open INOUTMXBREP

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@YYYYMM,
                                                               @Debit,@Credit,@EAMOUNT,@STRZhaiYao,@ItemBM

		Select @ItemBM00='AAAA'

	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
                       
			  SELECT  @NewYYYYMM=substring(@YYYYMM,1,4)+'年'+substring(@YYYYMM,5,2)+'月'


			IF   @ItemBM00<>@ItemBM 
			Begin

		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
	
			  select @BILLCODE=fullname,@JHD=JHD from ItemInfo where ItemBM=@ItemBM

	                  SELECT @BAMOUNT=BAMOUNT  FROM CW_billflow  WHERE  ItemBM=@ItemBM  AND YYYYMM=@Begin_YYYYMM   AND YYYYMMBILL=0
        	                                                      
	                  INSERT    INTO   #temptable2  (ID,BILLDATE, zhaiyao,EAMOUNT,NewYYYYMM,BILLCODE,ItemBM,JHD)
                                           VALUES  (@COUNTID ,@Begin_Date, '期初余额',@BAMOUNT,@NewYYYYMM,@BILLCODE,@ItemBM,@JHD)
			
				Select @ItemBM00=@ItemBM
			end


	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID


                    INSERT    INTO   #temptable2  (ID,BILLID,BILLTYPE, BILLDATE,NewYYYYMM,
                                                               Debit,Credit,EAMOUNT,zhaiyao,Memo,JHD)
                                           VALUES  (@COUNTID,@BILLID,@BILLTYPE, @BILLDATE,@NewYYYYMM,
                                                               @Debit,@Credit,@EAMOUNT,@STRZhaiYao,@Memo,@JHD)

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@YYYYMM,
                                                               @Debit,@Credit,@EAMOUNT,@STRZhaiYao,@ItemBM
 

	    END           ------- INOUTMXBREP  WHILE
	    close INOUTMXBREP
	    deallocate INOUTMXBREP




--------------------------

 SELECT *  FROM #temptable2         ORDER BY ID















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG



















------------------

CREATE PROCEDURE [Check_BILL_NO] (@Table     varchar(30), 
                  @BILLCODE  varchar(50),      -- 出入库标志（单据开头表示RK表示入库，CK表示出库）
                  @FlagCun int output --单号
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --当前会计年月     
declare @idd varchar(8)                     --序列号
declare @BILLNOFLAG  varchar(1)                     --单据格式
declare @BILLW  varchar(20)                     --单据格式
begin

       SET @FlagCun=0
                                  --------- 入库单号 ---------       
      if @Table='STOREZCDM'
      begin
                 IF exists(select * from STOREZCDM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STOREYunFeiFKM'  
      begin
                 IF exists(select * from STOREYunFeiFKM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='INVOICEM'
      begin
                 IF exists(select * from INVOICEM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end


      if @Table='STOREGJRKM'
      begin
                 IF exists(select * from STOREGJRKM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end

      if @Table='STORELiuHM'
      begin
                 IF exists(select * from STORELiuHM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STOREXSDDM'
      begin
                 IF exists(select * from STOREXSDDM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STORECGDDM'
      begin
                 IF exists(select * from STORECGDDM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STORECGTHM'
      begin
                 IF exists(select * from STORECGTHM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STOREXSTHM'
      begin
                 IF exists(select * from STOREXSTHM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STOREFYKZM'
      begin
                 IF exists(select * from STOREFYKZM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STOREQTSRM'
      begin
                 IF exists(select * from STOREQTSRM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STOREMOVEM'
      begin
                 IF exists(select * from STOREMOVEM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STOREXSSKM'
      begin
                 IF exists(select * from STOREXSSKM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STORECGFKM'
      begin
                 IF exists(select * from STORECGFKM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STORECGRKM'
      begin
                 IF exists(select * from STORECGRKM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STOREXSCKM'
      begin
                 IF exists(select * from STOREXSCKM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end

      if @Table='STORECKDBM'
      begin
                 IF exists(select * from STORECKDBM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STORECKPDM'
      begin
                 IF exists(select * from STORECKPDM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STOREQTRKM'
      begin
                 IF exists(select * from STOREQTRKM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end

      if @Table='STOREQTCKM'
      begin
                 IF exists(select * from STOREQTCKM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STOREGJRKM'
      begin
                 IF exists(select * from STOREGJRKM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STOREJGDM'
      begin
                 IF exists(select * from STOREJGDM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STOREQGDM'
      begin
                 IF exists(select * from STOREQGDM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end

      if @Table='STORECSHM'
      begin
                 IF exists(select * from STORECSHM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end
      if @Table='STOREZFDM'
      begin
                 IF exists(select * from STOREZFDM where Code=@BillCode) 
		 begin
		       SET @FlagCun=1
		 end
      end



END










----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG







--------------------------------------------------------------------

---此过程取得单据的标识   ID
---此过程取得单据的标识   ID 为8位字符串

CREATE PROCEDURE [dbo].[Check_Cred_Code_NO] (@BILLID VARCHAR(20),@CredTypeID int ,@CredNo int ,@CredCode int,@CredNoCF int  output,@CredCodeCF int  output)
AS 
 
  declare @curKeyValue VARCHAR(20)
  declare @NextKeyValue VARCHAR(20)
  declare @YYYYMM varchar(6)                   --会计年月     
  declare @MAXBILLDATE DATEtime 
  declare @MINBILLDATE DATEtime 

BEGIN
--- 	 set @curkeyvalue='00000000'

		exec Get_Max_Min_Date @MAXBILLDATE output,@MINBILLDATE output


	if exists(select *  from CW_PingZhengM   where BILLDate >@MINBILLDATE AND BILLDate <= @MAXBILLDATE  and BILLID<>@BILLID and CredNo=@CredNo)
	begin
		set @CredNoCF=1
	end
	else
	begin
		set @CredNoCF=0
	end

	if exists(select *  from CW_PingZhengM   where BILLDate >@MINBILLDATE AND BILLDate <= @MAXBILLDATE AND CredTypeID=@CredTypeID and BILLID<>@BILLID and CredCode=@CredCode)
	begin
		set @CredCodeCF=1
	end
	else
	begin
		set @CredCodeCF=0
	end







END
  







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG






















CREATE PROCEDURE [DANJuXiaoShu_SET]  
                 (
                  @UnitQtySTR varchar(10),      ---单据编号   
                  @QuanTITYSTR varchar(10)      ---单据编号   
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---是否现款标志
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @VENDORID   varchar(15)               --明细存货编号
declare @String_QUANTITY   varchar(100)               --明细存货编号
declare @String_UNITQTY   varchar(100)               --明细存货编号



     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_QGD   --事物开始


       exec ('ALTER TABLE STORECSHD  ALTER COLUMN [QUANTITY] [numeric](20, '+@QuanTITYSTR+') NULL ')

       exec ('ALTER TABLE STORECSHD  ALTER COLUMN [UNITQTY] [numeric](20, '+@UnitQtySTR+') NULL ')

       exec ('ALTER TABLE STORECGDDD  ALTER COLUMN [QUANTITY] [numeric](20, '+@QuanTITYSTR+') NULL ')

       exec ('ALTER TABLE STORECGDDD  ALTER COLUMN [UNITQTY] [numeric](20, '+@UnitQtySTR+') NULL ')

       exec ('ALTER TABLE STORECGRKD  ALTER COLUMN [QUANTITY] [numeric](20, '+@QuanTITYSTR+') NULL ')

       exec ('ALTER TABLE STORECGRKD  ALTER COLUMN [UNITQTY] [numeric](20, '+@UnitQtySTR+') NULL ')

       exec ('ALTER TABLE STORECGTHD  ALTER COLUMN [QUANTITY] [numeric](20, '+@QuanTITYSTR+') NULL ')

       exec ('ALTER TABLE STORECGTHD  ALTER COLUMN [UNITQTY] [numeric](20, '+@UnitQtySTR+') NULL ')

       exec ('ALTER TABLE STOREXSDDD  ALTER COLUMN [QUANTITY] [numeric](20, '+@QuanTITYSTR+') NULL ')

       exec ('ALTER TABLE STOREXSDDD  ALTER COLUMN [UNITQTY] [numeric](20, '+@UnitQtySTR+') NULL ')

       exec ('ALTER TABLE STOREXSCKD  ALTER COLUMN [QUANTITY] [numeric](20, '+@QuanTITYSTR+') NULL ')

       exec ('ALTER TABLE STOREXSCKD  ALTER COLUMN [UNITQTY] [numeric](20, '+@UnitQtySTR+') NULL ')

       exec ('ALTER TABLE STOREXSTHD  ALTER COLUMN [QUANTITY] [numeric](20, '+@QuanTITYSTR+') NULL ')

       exec ('ALTER TABLE STOREXSTHD  ALTER COLUMN [UNITQTY] [numeric](20, '+@UnitQtySTR+') NULL ')

       exec ('ALTER TABLE STOREQTRKD  ALTER COLUMN [QUANTITY] [numeric](20, '+@QuanTITYSTR+') NULL ')

       exec ('ALTER TABLE STOREQTRKD  ALTER COLUMN [UNITQTY] [numeric](20, '+@UnitQtySTR+') NULL ')

       exec ('ALTER TABLE STOREQTCKD  ALTER COLUMN [QUANTITY] [numeric](20, '+@QuanTITYSTR+') NULL ')

       exec ('ALTER TABLE STOREQTCKD  ALTER COLUMN [UNITQTY] [numeric](20, '+@UnitQtySTR+') NULL ')

       exec ('ALTER TABLE STORECKDBD  ALTER COLUMN [QUANTITY] [numeric](20, '+@QuanTITYSTR+') NULL ')

       exec ('ALTER TABLE STORECKDBD  ALTER COLUMN [UNITQTY] [numeric](20, '+@UnitQtySTR+') NULL ')

       exec ('ALTER TABLE STOREJGDD  ALTER COLUMN [QUANTITY] [numeric](20, '+@QuanTITYSTR+') NULL ')

       exec ('ALTER TABLE STOREJGDD  ALTER COLUMN [UNITQTY] [numeric](20, '+@UnitQtySTR+') NULL ')

       exec ('ALTER TABLE STOREQGDD  ALTER COLUMN [QUANTITY] [numeric](20, '+@QuanTITYSTR+') NULL ')

       exec ('ALTER TABLE STOREQGDD  ALTER COLUMN [UNITQTY] [numeric](20, '+@UnitQtySTR+') NULL ')

       exec ('ALTER TABLE STOREQGADD  ALTER COLUMN [QUANTITY] [numeric](20, '+@QuanTITYSTR+') NULL ')

       exec ('ALTER TABLE STOREQGADD  ALTER COLUMN [UNITQTY] [numeric](20, '+@UnitQtySTR+') NULL ')









   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin  
    commit   transaction trans_QGD
   end
   else
   begin
      rollback transaction trans_QGD
   end


















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG









--------------------------------------------------------------------插入月结记录

CREATE PROCEDURE [DetailBillFlow_insert_YYYYMM]  
                 (	
	 @ITEMNO varchar(8),
	@GOODSID varchar(20),
	@STOREID varchar(8),
	@qty  NUMERIC(20,10) ,
	@PRICE  NUMERIC(20,10) ,
	 @DetailBillFlowID  varchar(8),
              @BILLID varchar(22)      ---单据编号   
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @NEWID varchar(15)               --明细存货编号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @B_CODE VARCHAR(25)
declare @B_ID INTEGER

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       

            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
	            IF (@INF_COSTINGTYPEID IN(1,3,6 ) )  AND 
                                               (not exists(select *  from DETAILBILLFLOW  where 
             		                                    (rtrim(GOODSID) = @GOODSID)
                           	                   and(rtrim(STOREID) = @STOREID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
		    insert into DetailBillFlow 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
		     BQTY,BPRICE,BAMOUNT,INQTY,INPRICE,OUTQTY,OUTPRICE,
		     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,INF_COSTINGTYPEID,
		     BATCHREFID,REFQTY,REFCOUNT )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@itemNo,@GoodsID,
		     0,0,0,0,0,Null,Null,
		     @QTY,@price,@StoreID,'F',@inoutFlag,@QTY*@PRICE,null,@INF_COSTINGTYPEID,
		     @B_ID,0,0  )    
	            END      ------IF   END
----------------------------------对于三种的计算方法的程序都是一样的只是判断条件不一样




----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














----------------------------------------------------------------------------
CREATE PROCEDURE [FYKZBILLTREE]  (  @INSQLSTRING  varchar(300)    )  --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 

Declare @SQL				varchar(8000)

 
BEGIN

	SELECT @SQL= 'select SUBSTRING(GOODSNOJS,1,4) as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWFYKZJSNO'
	SELECT @SQL=@SQL+'  WHERE   SUBSTRING(GOODSNOJS,1,4) in (select lcode FROM OUTTYPE)    ' +@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY SUBSTRING(GOODSNOJS,1,4)'
	SELECT @SQL=@SQL+' union '
	SELECT @SQL=@SQL+' select SUBSTRING(GOODSNOJS,5,4) as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWFYKZJSNO'
	SELECT @SQL=@SQL+'  where   SUBSTRING(GOODSNOJS,5,4) in (select lcode FROM OUTTYPE) '+@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY SUBSTRING(GOODSNOJS,5,4)'
	SELECT @SQL=@SQL+' union '
	SELECT @SQL=@SQL+' select SUBSTRING(GOODSNOJS,9,4) as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWFYKZJSNO'
	SELECT @SQL=@SQL+'  where   SUBSTRING(GOODSNOJS,9,4) in (select lcode FROM OUTTYPE) '+@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY SUBSTRING(GOODSNOJS,9,4)'
	SELECT @SQL=@SQL+' union '
	SELECT @SQL=@SQL+' select SUBSTRING(GOODSNOJS,13,4) as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWFYKZJSNO'
	SELECT @SQL=@SQL+'  where   SUBSTRING(GOODSNOJS,13,4) in (select lcode FROM OUTTYPE) '+@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY SUBSTRING(GOODSNOJS,13,4)'
	SELECT @SQL=@SQL+' union '
	SELECT @SQL=@SQL+' select SUBSTRING(GOODSNOJS,17,4) as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWFYKZJSNO'
	SELECT @SQL=@SQL+'  where   SUBSTRING(GOODSNOJS,17,4) in (select lcode FROM OUTTYPE) '+@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY SUBSTRING(GOODSNOJS,17,4)'
	SELECT @SQL=@SQL+' union '
	SELECT @SQL=@SQL+' select SUBSTRING(GOODSNOJS,21,4) as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWFYKZJSNO'
	SELECT @SQL=@SQL+'  where   SUBSTRING(GOODSNOJS,21,4) in (select lcode FROM OUTTYPE) '+@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY SUBSTRING(GOODSNOJS,21,4)'
	SELECT @SQL=@SQL+' union '
	SELECT @SQL=@SQL+' select  STOREID as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWFYKZJSNO'
	SELECT @SQL=@SQL+'  where   1 = 1 '+@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY STOREID '
		EXEC(@SQL)
----注意OUTTYPE  中的LCODE不能和GOODS中的STOREID 重码，以后补充检测过程
------------------------------------------------------------------------------------


END







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













CREATE PROCEDURE GETALLPRICE(@GOODSID  varchar(20)  ,         ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
						           @DXSTOPPRICE   NUMERIC(20,10)    OUTPUT,
						           @DXSDOWNPRICE   NUMERIC(20,10)    OUTPUT,
						           @DXSAVGPRICE   NUMERIC(20,10)    OUTPUT,
						           @MXSTOPPRICE   NUMERIC(20,10)    OUTPUT,
						           @MXSDOWNPRICE   NUMERIC(20,10)    OUTPUT,
						           @MXSAVGPRICE   NUMERIC(20,10)    OUTPUT,
						           @DCGTOPPRICE   NUMERIC(20,10)    OUTPUT,
						           @DCGDOWNPRICE   NUMERIC(20,10)    OUTPUT,
						           @DCGAVGPRICE   NUMERIC(20,10)    OUTPUT,
						           @MCGTOPPRICE   NUMERIC(20,10)    OUTPUT,
						           @MCGDOWNPRICE   NUMERIC(20,10)    OUTPUT,
						           @MCGAVGPRICE   NUMERIC(20,10)    OUTPUT,
						           @MEQTY   NUMERIC(20,10)    OUTPUT,
						           @EQTY   NUMERIC(20,10)    OUTPUT
                         
                                                      )   --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @YYYYMM  varchar(8),      --------为当前会计期间
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000)
Declare    @SUM_1   NUMERIC(20,6)   
Declare    @SUM_0   NUMERIC(20,6)   
Declare    @SUM_unitqty   NUMERIC(20,6)   
Declare    @MXSTOPPRICE_1   NUMERIC(20,6)   
Declare    @MXSDOWNPRICE_1   NUMERIC(20,6)   
Declare    @MCGTOPPRICE_1   NUMERIC(20,6)   
Declare    @MCGDOWNPRICE_1   NUMERIC(20,6)   
Declare    @SQLSTR00   varchar(8000)

set @temp_year  = convert(varchar,year(getdate()))
set @temp_month = substring('00',1,2-len(convert(varchar,month(getdate()))))+convert(varchar,month(getdate()))
set @temp_day   = substring('00',1,2-len(convert(varchar,day(getdate()))))+convert(varchar,day(getdate()))
set @now_date   = @temp_year + @temp_month +@temp_day

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
Create Table #VIEWXSCK00
      (   GOODSID  nvarchar(50)  NULL,
	[unitprice] NUMERIC(20,10)  NULL ,
	[UNITQTY] NUMERIC(20,10)  NULL ,
	[quantity] NUMERIC(20,10)  NULL ,
	[PRICETYPE] int
		)

     select  @SQLSTR00=' INSERT INTO #VIEWXSCK00 Select top 10  GOODSID,unitprice,UNITQTY,quantity,PRICETYPE from   VIEWXSCKGOODSCODE WHERE GOODSID='+ @GOODSID +' order by  billdate  desc'
     exec (@SQLSTR00)

                      SELECT @DXSTOPPRICE=(SELECT isnull(max(unitprice),0)  AS  unitprice  FROM    #VIEWXSCK00  WHERE PRICETYPE=1)


                      SELECT @DXSDOWNPRICE=(SELECT isnull(mIN(unitprice),0)  AS  unitprice  FROM   #VIEWXSCK00  where PRICETYPE=1)
                      
                      SELECT @DXSAVGPRICE=(SELECT isnull(sum(unitprice*quantity)/sum(quantity),0)   AS  unitprice  FROM     #VIEWXSCK00  WHERE PRICETYPE=1 AND  quantity  >0 )  

---                      SELECT @MXSTOPPRICE=(SELECT isnull(max(unitprice),0)  AS  unitprice  FROM    VIEWXSCKGOODSCODE   where BILLID IN (Select top 10 BILLID from   VIEWXSCKGOODSCODE  WHERE PRICETYPE=0  AND  GOODSID=@GOODSID order by  billdate  desc))

                      SELECT @MXSTOPPRICE=(SELECT isnull(max(unitprice),0)  AS  unitprice  FROM     #VIEWXSCK00  WHERE PRICETYPE=0  )

                      SELECT @MXSTOPPRICE_1=(SELECT isnull(max(unitprice*quantity/UNITQTY),0)  AS  unitprice  FROM    #VIEWXSCK00 WHERE PRICETYPE=1 AND UNITQTY >0  )
				iF  @MXSTOPPRICE < @MXSTOPPRICE_1  
				begin
				   set  @MXSTOPPRICE = @MXSTOPPRICE_1
				end


                      SELECT @MXSDOWNPRICE=(SELECT isnull(MIN(unitprice),0)  AS  unitprice  FROM     #VIEWXSCK00   WHERE PRICETYPE=0  )

                      SELECT @MXSDOWNPRICE_1=(SELECT isnull(MIN(unitprice*quantity/UNITQTY),0)  AS  unitprice  FROM     #VIEWXSCK00  WHERE PRICETYPE=1 AND UNITQTY >0 )

				iF  (@MXSDOWNPRICE > @MXSDOWNPRICE_1)  OR (@MXSDOWNPRICE =0)
				begin
				   set  @MXSDOWNPRICE = @MXSDOWNPRICE_1
				end


                      SELECT @SUM_1=(SELECT   isnull(sum(unitprice*quantity),0)  FROM     #VIEWXSCK00 WHERE PRICETYPE=1  AND  unitqty  >0 )  
                      SELECT @SUM_0=(SELECT   isnull(sum(unitprice*unitqty),0)  FROM     #VIEWXSCK00  WHERE PRICETYPE=0  AND  unitqty  >0 )  
                      SELECT @SUM_unitqty=(SELECT   sum(unitqty)  FROM    #VIEWXSCK00  WHERE   unitqty  >0 )  
		      IF isnull(@SUM_unitqty,0) <>0	
                      SELECT @MXSAVGPRICE=(@SUM_1+@SUM_0)/@SUM_unitqty
		      ELSE
                      SELECT @MXSAVGPRICE=0




Create Table #VIEWCGRK00
      (   GOODSID  nvarchar(50)  NULL,
	[unitprice] NUMERIC(20,10)  NULL ,
	[UNITQTY] NUMERIC(20,10)  NULL ,
	[quantity] NUMERIC(20,10)  NULL ,
	[PRICETYPE] int
		)

     select  @SQLSTR00=' INSERT INTO #VIEWCGRK00 Select top 10  GOODSID,unitprice,UNITQTY,quantity,PRICETYPE from   VIEWCGRKGOODSCODE WHERE GOODSID='+ @GOODSID +' order by  billdate  desc'
     exec (@SQLSTR00)

                      SELECT @DCGTOPPRICE=(SELECT isnull(max(unitprice),0)  AS  unitprice  FROM    #VIEWCGRK00  WHERE PRICETYPE=1)


                      SELECT @DCGDOWNPRICE=(SELECT isnull(mIN(unitprice),0)  AS  unitprice  FROM   #VIEWCGRK00  where PRICETYPE=1)
                      
                      SELECT @DCGAVGPRICE=(SELECT isnull(sum(unitprice*quantity)/sum(quantity),0)   AS  unitprice  FROM     #VIEWCGRK00  WHERE PRICETYPE=1 AND  quantity  >0 )  

---                      SELECT @MCGTOPPRICE=(SELECT isnull(max(unitprice),0)  AS  unitprice  FROM    VIEWCGRKGOODSCODE   where BILLID IN (Select top 10 BILLID from   VIEWCGRKGOODSCODE  WHERE PRICETYPE=0  AND  GOODSID=@GOODSID order by  billdate  desc))

                      SELECT @MCGTOPPRICE=(SELECT isnull(max(unitprice),0)  AS  unitprice  FROM     #VIEWCGRK00  WHERE PRICETYPE=0  )

                      SELECT @MCGTOPPRICE_1=(SELECT isnull(max(unitprice*quantity/UNITQTY),0)  AS  unitprice  FROM    #VIEWCGRK00 WHERE PRICETYPE=1 AND UNITQTY >0  )
				iF  @MCGTOPPRICE < @MCGTOPPRICE_1  
				begin
				   set  @MCGTOPPRICE = @MCGTOPPRICE_1
				end


                      SELECT @MCGDOWNPRICE=(SELECT isnull(MIN(unitprice),0)  AS  unitprice  FROM     #VIEWCGRK00   WHERE PRICETYPE=0  )

                      SELECT @MCGDOWNPRICE_1=(SELECT isnull(MIN(unitprice*quantity/UNITQTY),0)  AS  unitprice  FROM     #VIEWCGRK00  WHERE PRICETYPE=1 AND UNITQTY >0 )

				iF  (@MCGDOWNPRICE > @MCGDOWNPRICE_1)  OR (@MCGDOWNPRICE =0)
				begin
				   set  @MCGDOWNPRICE = @MCGDOWNPRICE_1
				end


                      SELECT @SUM_1=(SELECT   isnull(sum(unitprice*quantity),0)  FROM     #VIEWCGRK00 WHERE PRICETYPE=1  AND  unitqty  >0 )  
                      SELECT @SUM_0=(SELECT   isnull(sum(unitprice*unitqty),0)  FROM     #VIEWCGRK00  WHERE PRICETYPE=0  AND  unitqty  >0 )  
                      SELECT @SUM_unitqty=(SELECT   sum(unitqty)  FROM    #VIEWCGRK00  WHERE   unitqty  >0 )  
		      IF isnull(@SUM_unitqty,0) <>0	
                      SELECT @MCGAVGPRICE=(@SUM_1+@SUM_0)/@SUM_unitqty
		      ELSE
                      SELECT @MCGAVGPRICE=0





----------------------------------------------------
		SELECT @SQLSTR='	INSERT INTO  #GOODSTEMP      select  I.GOODSID,       '
		SELECT @SQLSTR=@SQLSTR+'  ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0)  as MEQTY, '   --期末数量
		SELECT @SQLSTR=@SQLSTR+'  ISNULL(B.BQTY,0)+ isnull(E.INQTY,0)  as EQTY   '   --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from Goods    AS  I'
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(INQTY*INOUTFLAG)  as INQTY  ,sum(MINQTY*INOUTFLAG)  as MINQTY '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(BQTY) as BQTY ,sum(MBQTY) as MBQTY'
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where    I.GOODSID   = ' +char(39)+@GOODSID+char(39)
------------------------------------------------------------------------
Create Table #GOODSTEMP
      (   GOODSID  nvarchar(50)  NULL,
	[MEQTY] NUMERIC(20,10)  NULL ,
	[EQTY] NUMERIC(20,10)  NULL 
		)

 		EXEC(@SQLSTR)
                      SELECT  @EQTY=(SELECT isnull(EQTY,0)  AS  EQTY  FROM #GOODSTEMP )
                      SELECT  @MEQTY=(SELECT isnull(MEQTY,0)  AS  MEQTY  FROM #GOODSTEMP )







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












----------------------------------------------------------------------------

CREATE PROCEDURE GETCLIENTIDEAMOUNT(@CLIENTID varchar(8) ,                        -----如果为0000则全部仓库
						           @EAMOUNT   NUMERIC(20,10)    OUTPUT
                         
                                                      )   --APSOFTENCRYPTION       WITH ENCRYPTION
as




Declare    @MAXID   varchar(80)

  SELECT  @MAXID=MAX(ID)  FROM CLIENTbillflow  WHERE  CLIENTID=@CLIENTID  AND YYYYMMBILL=1

                        IF @MAXID IS NULL
 			BEGIN
			SET  @EAMOUNT=0
			END
                        ELSE
			BEGIN
                         SELECT @EAMOUNT=EAMOUNT   FROM   CLIENTbillflow  WHERE ID=@MAXID
			END








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











----------------------------------------------------------------------------

CREATE PROCEDURE GETGOODSIDEQTY(@STOREID varchar(8) ,                        -----如果为0000则全部仓库
						           @GOODSID  varchar(20)  ,         ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
                                                                                           @YYYYMM  varchar(8),      --------为当前会计期间
						           @EQTY   NUMERIC(20,10)    OUTPUT
                         
                                                      )   --APSOFTENCRYPTION       WITH ENCRYPTION
as



Declare 
        @SQLSTR   varchar(8000)

Declare    @GOODSIDSTR   varchar(80)
Declare    @STOREIDSTR   varchar(80)


----------------------------------------------------
		 SET @GOODSIDSTR = '  AND   GOODSID = '+char(39)+ @GOODSID+char(39)
		 IF   @STOREID='0000'
		BEGIN
		 SET @STOREIDSTR = '    '
		END
		ELSE
		BEGIN
		 SET @STOREIDSTR = '  AND   STOREID = '+char(39)+ @STOREID+char(39)
		END
		SELECT @SQLSTR='	INSERT  #GOODSTEMP      select  I.GOODSID,       '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)+ isnull(E.INQTY,0)  as EQTY '   --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from Goods    AS  I'
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(INQTY*INOUTFLAG)  as INQTY  '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)  +@STOREIDSTR +@GOODSIDSTR               --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(BQTY) as BQTY '
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) +@STOREIDSTR+@GOODSIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where    I.GOODSID   = ' +char(39)+@GOODSID+char(39)
------------------------------------------------------------------------
Create Table #GOODSTEMP
      (   GOODSID  nvarchar(50)  NULL,
	[EQTY] NUMERIC(20,10)  NULL 
		)

 		EXEC(@SQLSTR)
                      SELECT  @EQTY=(SELECT isnull(EQTY,0)  AS  EQTY  FROM #GOODSTEMP )





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











----------------------------------------------------------------------------

CREATE PROCEDURE GETGOODSIDMEQTY(@STOREID varchar(8) ,                        -----如果为0000则全部仓库
						           @GOODSID  varchar(20)  ,         ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
                                                                                           @YYYYMM  varchar(8),      --------为当前会计期间
						           @MEQTY   NUMERIC(20,10)    OUTPUT
                         
                                                      )   --APSOFTENCRYPTION       WITH ENCRYPTION
as



Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000)

Declare    @GOODSIDSTR   varchar(80)
Declare    @STOREIDSTR   varchar(80)

set @temp_year  = convert(varchar,year(getdate()))
set @temp_month = substring('00',1,2-len(convert(varchar,month(getdate()))))+convert(varchar,month(getdate()))
set @temp_day   = substring('00',1,2-len(convert(varchar,day(getdate()))))+convert(varchar,day(getdate()))
set @now_date   = @temp_year + @temp_month +@temp_day

----------------------------------------------------
		 SET @GOODSIDSTR = '  AND   GOODSID = '+char(39)+ @GOODSID+char(39)
		 IF   @STOREID='0000'
		BEGIN
		 SET @STOREIDSTR = '    '
		END
		ELSE
		BEGIN
		 SET @STOREIDSTR = '  AND   STOREID = '+char(39)+ @STOREID+char(39)
		END
		SELECT @SQLSTR='	INSERT  #GOODSTEMP      select  I.GOODSID,       '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0)  as MEQTY '   --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from Goods    AS  I'
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(MINQTY*INOUTFLAG)  as MINQTY  '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)  +@STOREIDSTR +@GOODSIDSTR               --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(MBQTY) as MBQTY '
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) +@STOREIDSTR+@GOODSIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where    I.GOODSID   = ' +char(39)+@GOODSID+char(39)
------------------------------------------------------------------------
Create Table #GOODSTEMP
      (   GOODSID  nvarchar(50)  NULL,
	[MEQTY] NUMERIC(20,10)  NULL 
		)

 		EXEC(@SQLSTR)
                      SELECT  @MEQTY=(SELECT isnull(MEQTY,0)  AS  MEQTY  FROM #GOODSTEMP )








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------

CREATE PROCEDURE GETGOODSSQL(@STOREID varchar(8) ,                        -----如果为0000则全部仓库
						           @LCODE  varchar(10),             ---如果LCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSCODE  varchar(20),             ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSNAME  varchar(20),             ---如果GOODSNAME  为‘GGGG’表示不对类别进行查询
                                                                                           @INF_COSTINGTYPEID   smallint      --------同价调拨标志   0  代表 不作为过滤条件
                         
                                                      )     --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @WHERESTING   varchar(1800),
        @STOREIDSTR   varchar(100)

--@WHERESTR='  and 1=1 '
		if     NOT (@LCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = '  AND   GOODSID IN ( select  GOODSID from Goods   where  LCODE LIKE   '+CHAR(39)+@LCODE+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  ='     '
 		END
		if     NOT (@GOODSCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   GOODSID IN ( select  GOODSID from Goods   where  CODE LIKE   '+CHAR(39)+'%'+@GOODSCODE+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  =@WHERESTING+'     '
 		END
		if     NOT (@GOODSNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   GOODSID IN ( select  GOODSID from Goods   where  NAME  LIKE   '+CHAR(39)+'%'+@GOODSNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END
		if     NOT (@INF_COSTINGTYPEID=0)
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND  GOODSID IN ( select  GOODSID from Goods   where INF_COSTINGTYPEID =  '+str(@INF_COSTINGTYPEID)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END
		if     NOT (@STOREID='0000')
                           BEGIN
	                           SELECT    @STOREIDSTR   = '  AND   STOREID =  '+@STOREID
                           END
                           ELSE
                           BEGIN
			SELECT    @STOREIDSTR   = '     '
 		END

                       print   @WHERESTING
----------------------------------------------------
                         SELECT  @SQLSTR=' SELECT  *  FROM GOODS WHERE   1 = 1  ' +@WHERESTING
		EXEC(@SQLSTR)






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












CREATE PROCEDURE GETGoodsIDEQTYANDALL(@GOODSID  varchar(20)  ,         ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
				   @StoreID  varchar(20), 
			           @EQTY   NUMERIC(20,10)    OUTPUT,
			           @StoreIDEQTY   NUMERIC(20,10)    OUTPUT
                                                      )   --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @YYYYMM  varchar(8),      --------为当前会计期间
        @SQLSTR   varchar(8000)


     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     

----------------------------------------------------
		SELECT @SQLSTR='	INSERT  #GOODSTEMP     select  I.GOODSID,       '
		SELECT @SQLSTR=@SQLSTR+'  ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0)  as MEQTY, '   --期末数量
		SELECT @SQLSTR=@SQLSTR+'  ISNULL(B.BQTY,0)+ isnull(E.INQTY,0)  as EQTY   '   --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from Goods    AS  I'
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(INQTY*INOUTFLAG)  as INQTY  ,sum(MINQTY*INOUTFLAG)  as MINQTY '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(BQTY) as BQTY ,sum(MBQTY) as MBQTY'
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where    I.GOODSID   = ' +char(39)+@GOODSID+char(39)
------------------------------------------------------------------------
Create Table #GOODSTEMP
      (   GOODSID  nvarchar(50)  NULL,
	[MEQTY] NUMERIC(20,10)  NULL ,
	[EQTY] NUMERIC(20,10)  NULL 
		)

 		EXEC(@SQLSTR)
                      SELECT  @EQTY=(SELECT isnull(EQTY,0)  AS  EQTY  FROM #GOODSTEMP )
--                      SELECT  @MEQTY=(SELECT isnull(MEQTY,0)  AS  MEQTY  FROM #GOODSTEMP )
---                      SELECT  @EQTY=(SELECT isnull(EQTY,0)  AS  EQTY  FROM #GOODSTEMP )

                      SELECT  @EQTY=0

                      EXEC   GETGOODSIDEQTY  @STOREID,@GOODSID,@YYYYMM,@EQTY=@STOREIDEQTY   OUTPUT







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG










--------------------------------------------------------------------

---此过程取得单据的标识   ID
---此过程取得单据的标识   ID 为8位字符串

CREATE PROCEDURE [GETKEYCodeKEYVALUE] (@TABLENAME VARCHAR(48),@Lcode VARCHAR(48),
				@R_KEYCode VARCHAR(20)  output,
				@R_KeyValue VARCHAR(20)  output)    --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 
  declare @curKEYCode VARCHAR(20)
  declare @NextKEYCode VARCHAR(20)
  declare @MaxCode VARCHAR(50)
  declare @SQLSTR VARCHAR(5000)
  declare @curKeyValue VARCHAR(20)
  declare @NextKeyValue VARCHAR(20)

BEGIN
--- 	 set @curKEYCode='00000000'
Create Table #TempCodeValue
      (   ABCD    varchar(50)  NULL
		)


		SET @SqlSTR=' INSERT  #TempCodeValue  '
		SET @SqlSTR=@SqlSTR+' select Max(Code) from '+@TableName+' where code like '+Char(39)+@Lcode+'%'+Char(39)		
		exec (@SqlSTR)
		Select @MaxCode=(SELect ABCD  from #TempCodeValue)


----Select substring('10.1.37',len('10.1')+2,len('10.1.37')-len('10.1')-1)

	  SET @curKEYCode=substring(@MaxCode,len(@Lcode)+2,len(@MaxCode)-len(@Lcode)-1)

	  If  (@curKEYCode<>'') and  (NOT (@curKEYCode IS NULL)) AND (CHARINDEX('.',@curKEYCode)=0)
	  begin
	          set @NextKEYCode = rtrim(convert(char,convert(int,@curKEYCode)+1))
		  set @R_KEYCode = @Lcode+'.'+@NextKEYCode

	  end
	  else
	  begin

		  select @curKEYCode=keyvalue from keyvaluetable   where TableName=@TableName 
        	  set @NextKEYCode = rtrim(convert(char,convert(int,@curKEYCode)+1))
	          set @NextKEYCode = substring('00000000',1,8-len(@NextKEYCode))+@NextKEYCode

		  if (@curKEYCode  is NULL)  or (not (len(@curKEYCode)=8 ) )
		  begin
		    set @R_KEYCode='00000001'
		    delete from keyvaluetable where TableName=@TableName
		    insert into keyvaluetable values (@TableName,@R_KEYCode)
		  end
		  else
		  begin
		    update keyvaluetable set keyvalue=@NextKEYCode    where TableName=@TableName
		    set @R_KEYCode = @NextKEYCode
		  end
	  end


-------------------以上部分是取Code------以下部分是取KeyValue---------------------------------

	  select @curkeyvalue=keyvalue from keyvaluetable   where TableName=@TableName 
          set @NextKeyValue = rtrim(convert(char,convert(int,@curkeyvalue)+1))
          set @NextKeyValue = substring('00000000',1,8-len(@NextKeyValue))+@NextKeyValue

	  if (@curkeyvalue  is NULL)  or (not (len(@curkeyvalue)=8 ) )
	  begin
	    set @R_KeyValue='00000001'
	    delete from keyvaluetable where TableName=@TableName
	    insert into keyvaluetable values (@TableName,@R_KeyValue)
	  end
	  else
	  begin
	    update keyvaluetable set keyvalue=@NextKeyValue    where TableName=@TableName
	    set @R_KeyValue = @NextKeyValue
	  end


END
  








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG









--------------------------------------------------------------------

---此过程取得单据的标识   ID
---此过程取得单据的标识   ID 为8位字符串

CREATE PROCEDURE [GETKEYVALUE] (@TABLENAME VARCHAR(48),@R_KeyValue VARCHAR(20)  output)    --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 
  declare @curKeyValue VARCHAR(20)
  declare @NextKeyValue VARCHAR(20)

BEGIN
--- 	 set @curkeyvalue='00000000'
	  select @curkeyvalue=keyvalue from keyvaluetable   where TableName=@TableName 
          set @NextKeyValue = rtrim(convert(char,convert(int,@curkeyvalue)+1))
          set @NextKeyValue = substring('00000000',1,8-len(@NextKeyValue))+@NextKeyValue

	  if (@curkeyvalue  is NULL)  or (not (len(@curkeyvalue)=8 ) )
	  begin
	    set @R_KeyValue='00000001'
	    delete from keyvaluetable where TableName=@TableName
	    insert into keyvaluetable values (@TableName,@R_KeyValue)
	  end
	  else
	  begin
	    update keyvaluetable set keyvalue=@NextKeyValue    where TableName=@TableName
	    set @R_KeyValue = @NextKeyValue
	  end
END
  







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













--------------------------------------------------------------------

---此过程取得单据的标识   ID
---此过程取得单据的标识   ID 为2位字符串

CREATE PROCEDURE [GETKEYVALUE00] (@TABLENAME VARCHAR(48),@R_KeyValue VARCHAR(2)  output)    --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 
  declare @curKeyValue VARCHAR(20)
  declare @NextKeyValue VARCHAR(20)

BEGIN
--- 	 set @curkeyvalue='00000000'
	  select @curkeyvalue=keyvalue from keyvaluetable   where TableName=@TableName 
          set @NextKeyValue = rtrim(convert(char,convert(int,@curkeyvalue)+1))
          set @NextKeyValue = substring('00',1,2-len(@NextKeyValue))+@NextKeyValue

	  if (@curkeyvalue  is NULL)  or (not (len(@curkeyvalue)=2 ) )
	  begin
	    set @R_KeyValue='01'
	    delete from keyvaluetable where TableName=@TableName
	    insert into keyvaluetable values (@TableName,@R_KeyValue)
	  end
	  else
	  begin
	    update keyvaluetable set keyvalue=@NextKeyValue    where TableName=@TableName
	    set @R_KeyValue = @NextKeyValue
	  end
END
  







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














--------------------------------------------------------------------

---此过程取得单据的标识   ID
---此过程取得单据的标识   ID 为2位字符串

CREATE PROCEDURE [GETKEYVALUE4] (@TABLENAME VARCHAR(48),@R_KeyValue VARCHAR(4)  output)    --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 
  declare @curKeyValue VARCHAR(20)
  declare @NextKeyValue VARCHAR(20)

BEGIN
--- 	 set @curkeyvalue='00000000'
	  select @curkeyvalue=keyvalue from keyvaluetable   where TableName=@TableName 
          set @NextKeyValue = rtrim(convert(char,convert(int,@curkeyvalue)+1))
          set @NextKeyValue = substring('0000',1,4-len(@NextKeyValue))+@NextKeyValue

	  if (@curkeyvalue  is NULL)  or (not (len(@curkeyvalue)=4 ) )
	  begin
	    set @R_KeyValue='0001'
	    delete from keyvaluetable where TableName=@TableName
	    insert into keyvaluetable values (@TableName,@R_KeyValue)
	  end
	  else
	  begin
	    update keyvaluetable set keyvalue=@NextKeyValue    where TableName=@TableName
	    set @R_KeyValue = @NextKeyValue
	  end
END
  








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












----------------------------------------------------------------------------

CREATE PROCEDURE GETVENDORIDEAMOUNT(@VENDORID varchar(8) ,                        -----如果为0000则全部仓库
						           @EAMOUNT   NUMERIC(20,10)    OUTPUT
                         
                                                      )   --APSOFTENCRYPTION       WITH ENCRYPTION
as




Declare    @MAXID   varchar(80)

  SELECT  @MAXID=MAX(ID)  FROM VENDORbillflow  WHERE  VENDORID=@VENDORID  AND YYYYMMBILL=1

                        IF @MAXID IS NULL
 			BEGIN
			SET  @EAMOUNT=0
			END
                        ELSE
			BEGIN
                         SELECT @EAMOUNT=EAMOUNT   FROM   VENDORbillflow  WHERE ID=@MAXID
			END








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











--------------------------------------------------------------------

---此过程取得单据的标识   ID
---此过程取得单据的标识   ID 为8位字符串

CREATE PROCEDURE [dbo].[GETXSPrice] (@GoodsID VARCHAR(48),@DXSPrice  NUMERIC(20,2)    OUTPUT,
							@MXSPrice   NUMERIC(20,10)    OUTPUT
)    --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 
  declare @SumAMT NUMERIC(20,10)
  declare @MinITEMNO  varchar(20)
  declare @SumQuantity NUMERIC(20,10)
  declare @printcount int

BEGIN

---------------取销售定价模式
---------------@printcount=1 按品种定价
---------------@printcount=2 按采购批次定价

---------------@

	          select  @printcount=printcount from ACCINFO where GUID='0001'
     if @printcount=2 
	    begin               
	          select  @MinITEMNO=Min(ITEMNO) from CGRKGoodsPrice where GOODSID=@GOODSID  AND ( DEQTY>0 OR MEQTY>0)
           if @MinITEMNO is not null
           begin
              select  @DXSPrice=ISNULL(DSPrice,0),@MXSPrice=ISNULL(MSPrice,0)  from CGRKGoodsPrice where ITEMNO=@MinITEMNO
			end
			else
			begin
              select  @DXSPrice=ISNULL(DSPrice,0) ,@MXSPrice=ISNULL(MQTYSPRICE,0)  from GOODS where  GOODSID=@GOODSID		
			end
        end
        else
        begin
              select  @DXSPrice=ISNULL(DSPrice,0) ,@MXSPrice=ISNULL(MQTYSPRICE,0)  from GOODS where  GOODSID=@GOODSID		
        end
               

END
  









----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG










--------------------------------------------------------------------

---此过程取得单据的标识   ID
---此过程取得单据的标识   ID 为8位字符串

CREATE PROCEDURE [GETXSPriceDays] (@GoodsID VARCHAR(48),@R_10DayPrce  NUMERIC(20,10)    OUTPUT,
							@R_20DayPrce  NUMERIC(20,10)    OUTPUT,
							@R_30DayPrce  NUMERIC(20,10)    OUTPUT,
							@R_60DayPrce  NUMERIC(20,10)    OUTPUT
)    --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 
  declare @SumAMT NUMERIC(20,10)
  declare @SumQuantity NUMERIC(20,10)

BEGIN

	  SELECT  @SumAMT=Sum(AMT) FROM VIEWXSCKGOODSCODE  where  billdate >= convert(varchar(10),dateadd(day ,-10 ,getdate()),120) 
	  SELECT  @SumQuantity=Sum(Quantity) FROM VIEWXSCKGOODSCODE where  billdate >= convert(varchar(10),dateadd(day ,-10 ,getdate()),120) 

          Select @R_10DayPrce=@SumAMT/@SumQuantity                                        

	  SELECT  @SumAMT=Sum(AMT) FROM VIEWXSCKGOODSCODE  where  billdate >= convert(varchar(10),dateadd(day ,-20 ,getdate()),120) 
	  SELECT  @SumQuantity=Sum(Quantity) FROM VIEWXSCKGOODSCODE where  billdate >= convert(varchar(10),dateadd(day ,-20 ,getdate()),120) 

          Select @R_20DayPrce=@SumAMT/@SumQuantity                                        

	  SELECT  @SumAMT=Sum(AMT) FROM VIEWXSCKGOODSCODE  where  billdate >= convert(varchar(10),dateadd(day ,-30 ,getdate()),120) 
	  SELECT  @SumQuantity=Sum(Quantity) FROM VIEWXSCKGOODSCODE where  billdate >= convert(varchar(10),dateadd(day ,-30 ,getdate()),120) 

          Select @R_30DayPrce=@SumAMT/@SumQuantity                                        

	  SELECT  @SumAMT=Sum(AMT) FROM VIEWXSCKGOODSCODE  where  billdate >= convert(varchar(10),dateadd(day ,-60 ,getdate()),120) 
	  SELECT  @SumQuantity=Sum(Quantity) FROM VIEWXSCKGOODSCODE where  billdate >= convert(varchar(10),dateadd(day ,-60 ,getdate()),120) 

          Select @R_60DayPrce=@SumAMT/@SumQuantity                                        



END
  








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












----------------------------------------------------------------------------
CREATE PROCEDURE [GET_APRICE ]  (  @GOODSID varchar(22),      ---单据编号   
	     @STOREID varchar(22),  
                  @FLAGPOST INT,      ---记帐标志
  	     @DETAILBILLFLOWID varchar(30), 
  	     @REDETAILBILLFLOWID varchar(30), 
	@APRICE NUMERIC(20,10)   output)     --APSOFTENCRYPTION       WITH ENCRYPTION
AS 


declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @STOREHSFS   INTEGER
declare @MAXID   varchar(30)

 
BEGIN

	       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )      


            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)

                 SELECT   @APRICE=0.00 

	    IF   @FLAGPOST = 0  --THEN
	    BEGIN
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
			IF  @INF_COSTINGTYPEID=1    OR  @INF_COSTINGTYPEID=3
			BEGIN
                                            SELECT  @MAXID=(SELECT MAX(ID)  FROM  DETAILBILLFLOW   WHERE GOODSID=@GOODSID  AND STOREID=@STOREID  and  YYYYMMBILL=1)
		                 SELECT  @APRICE =EPRICE    FROM DETAILBILLFLOW  WHERE GOODSID = @GOODSID  AND STOREID=@STOREID  AND ID=@MAXID
			END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
			IF  @INF_COSTINGTYPEID=1    OR @INF_COSTINGTYPEID=3
			BEGIN
                                            SELECT  @MAXID=(SELECT MAX(ID)  FROM  DETAILBILLFLOW   WHERE GOODSID=@GOODSID and  YYYYMMBILL=1)
		                 SELECT  @APRICE = EPRICE    FROM DETAILBILLFLOW   WHERE GOODSID = @GOODSID  AND ID=@MAXID
			END
                            END
 		IF  @INF_COSTINGTYPEID=2    
		BEGIN
	                 SELECT  @APRICE =INPRICE    FROM DETAILBILLFLOW  
             	               WHERE ID= @REDETAILBILLFLOWID
		END
	    END
	    IF  ( @FLAGPOST = 1) 
	    BEGIN
	                 SELECT  @APRICE =INPRICE    FROM DETAILBILLFLOW  
             		               WHERE ID= @DETAILBILLFLOWID
                              if  @APRICE is null
                              begin
                                      set @APRICE=0.00
		   end
	    END



END
  







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG























------------------

CREATE PROCEDURE [GET_BILL_NO] (@Table     varchar(30), 
                  @sysdate   varchar(10),         ---系统时间格式为  2004-02-02
                  @INOUTFlag varchar(2),      -- 出入库标志（单据开头表示RK表示入库，CK表示出库）
                  @bill_no_selfd varchar(22) output --单号
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --当前会计年月     
declare @idd varchar(8)                     --序列号
declare @BILLNOFLAG  varchar(1)                     --单据格式
declare @BILLW  varchar(20)                     --单据格式
declare @YYYYMM_FLAG  INTEGER

begin

       set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
               ---@BILLNOFLAG  返回单据号的格式{[0]代表RK-2004-03-12-0001;[1]代表RK-2004-03-0001}
       set @BILLNOFLAG   = (select optionvalue from accoptions where optionname ='BILLNOFLAG')
       SET @BILLW='DSDSD'

-------解决所在的会计期间的
-------根据日期来判断所在的会计区间
-------
      EXEC  BETWEEN_CURR_YYYYMM  @sysdate , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@YYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

----        print @YYYYMM

if (@BILLNOFLAG = '1')
begin           
                                  --------- 入库单号 ---------
      if @Table='STOREZFDM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREZFDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREZFDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREXSFPM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREXSFPM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREXSFPM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STORECGFPM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STORECGFPM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STORECGFPM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREZCDM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREZCDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREZCDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
       
      if @Table='STOREQGADM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREQGADM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREQGADM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end

      if @Table='STOREYunFeiFKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREYunFeiFKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREYunFeiFKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='INVOICEM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from INVOICEM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from INVOICEM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end

      if @Table='STOREZZHPM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREZZHPM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREZZHPM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STORECXHPM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STORECXHPM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STORECXHPM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STORECPJCMBM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STORECPJCMBM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STORECPJCMBM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREPLLLMBM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREPLLLMBM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREPLLLMBM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREZZCXMBM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREZZCXMBM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREZZCXMBM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREDBCKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREDBCKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREDBCKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREDBCKTHM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREDBCKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREDBCKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end

      if @Table='STOREJYCKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREJYCKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREJYCKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREJYCKTHM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREJYCKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREJYCKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREDXRKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREDXRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREDXRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREDXRKTHM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREDXRKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREDXRKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREGJRKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREGJRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREGJRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREGJRKTHM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREGJRKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREGJRKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREDBRKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREDBRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREDBRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREDBRKTHM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREDBRKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREDBRKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREZSRKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREZSRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREZSRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREZSRKTHM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREZSRKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREZSRKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREJYRKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREJYRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREJYRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREJYRKTHM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREJYRKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREJYRKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end

      if @Table='STOREQTRKTHM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREQTRKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREQTRKTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STORELiuHM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STORELiuHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STORELiuHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREXSDDM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREXSDDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREXSDDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STORECGDDM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STORECGDDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STORECGDDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STORECGTHM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STORECGTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STORECGTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREXSTHM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREXSTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREXSTHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREFYKZM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREFYKZM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREFYKZM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREQTSRM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREQTSRM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREQTSRM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREMOVEM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREMOVEM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREMOVEM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREXSSKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREXSSKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREXSSKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STORECGFKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STORECGFKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STORECGFKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STORECGRKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STORECGRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STORECGRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREXSCKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREXSCKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREXSCKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end

      if @Table='STORELLCKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STORELLCKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STORELLCKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STORECPJCM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STORECPJCM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STORECPJCM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STORECKDBM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STORECKDBM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STORECKDBM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STORECKPDM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STORECKPDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STORECKPDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREHPTJM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREHPTJM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREHPTJM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREHPBSM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREHPBSM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREHPBSM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREQTRKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREQTRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREQTRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end

      if @Table='STOREQTCKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREQTCKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREQTCKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREGJRKM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREGJRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREGJRKM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STORECSHM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STORECSHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STORECSHM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end
      if @Table='STOREQGDM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREQGDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREQGDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end

      if @Table='STOREJGDM'
      begin
	      if (select max(substring(CODE,12,4)) as maxid from STOREJGDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2) )) is null 
        	   select @idd ='0000'
	      else
        	   select @idd = (select max(substring(CODE,12,4)) as maxid from STOREJGDM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
      end




      set      @idd = rtrim(convert(char,convert(int,@idd)+1))
      set      @bill_no_selfd =@INOUTFlag+'-'+substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)+'-'+substring('0000',1,4-len(@idd))+@idd
end
--------------------------------------------------------------------------------------=====================
if ( @BILLNOFLAG = '0')
begin                                             --------- 入库单号 ---------       


      if @Table='STOREYunFeiFKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREYunFeiFKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREYunFeiFKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end

      if @Table='STORECXHPM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STORECXHPM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STORECXHPM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='INVOICEM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from INVOICEM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from INVOICEM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end

      if @Table='STOREZZHPM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREZZHPM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREZZHPM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREPLLLMBM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREPLLLMBM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREPLLLMBM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STORECPJCMBM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STORECPJCMBM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STORECPJCMBM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREZZCXMBM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREZZCXMBM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREZZCXMBM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREJYCKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREJYCKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREJYCKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREJYCKTHM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREJYCKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREJYCKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREDBCKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREDBCKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREDBCKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREDBCKTHM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREDBCKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREDBCKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREGJRKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREGJRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREGJRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREGJRKTHM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREGJRKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREGJRKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREDXRKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREDXRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREDXRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREDXRKTHM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREDXRKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREDXRKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREDBRKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREDBRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREDBRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREDBRKTHM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREDBRKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREDBRKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREZSRKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREZSRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREZSRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREZSRKTHM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREZSRKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREZSRKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREJYRKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREJYRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREJYRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREJYRKTHM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREJYRKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREJYRKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end

      if @Table='STOREQTRKTHM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREQTRKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREQTRKTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STORELiuHM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STORELiuHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STORELiuHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREXSDDM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREXSDDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREXSDDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STORECGDDM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STORECGDDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STORECGDDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STORECGTHM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STORECGTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STORECGTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREXSTHM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREXSTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREXSTHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREFYKZM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREFYKZM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREFYKZM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREQTSRM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREQTSRM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREQTSRM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREMOVEM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREMOVEM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREMOVEM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREXSSKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREXSSKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREXSSKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STORECGFKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STORECGFKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STORECGFKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STORECGRKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STORECGRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STORECGRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end

      if @Table='STOREXSCKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREXSCKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREXSCKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end

      if @Table='STORELLCKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STORELLCKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STORELLCKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end

      if @Table='STORECPJCM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STORECPJCM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STORECPJCM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end

      if @Table='STORECKDBM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STORECKDBM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STORECKDBM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STORECKPDM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STORECKPDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STORECKPDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end

      if @Table='STOREHPTJM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREHPTJM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREHPTJM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREHPBSM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREHPBSM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREHPBSM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREQTRKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREQTRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREQTRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end

      if @Table='STOREQTCKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREQTCKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREQTCKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREGJRKM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREGJRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREGJRKM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STORECSHM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STORECSHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STORECSHM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end

      if @Table='STOREJGDM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREJGDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREJGDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREQGDM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREQGDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREQGDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end

      if @Table='STOREQGADM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREQGADM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREQGADM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end

      if @Table='STOREZCDM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREZCDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREZCDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STOREXSFPM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREXSFPM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREXSFPM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end
      if @Table='STORECGFPM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STORECGFPM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STORECGFPM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end

      if @Table='STOREZFDM'
      begin
	      if (select max(substring(CODE,15,4)) as maxid from STOREZFDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate )) is null 
        	   select @idd ='0000'
	      else
	           select @idd = (select max(substring(CODE,15,4)) as maxid from STOREZFDM where (len(CODE)=18 and substring(CODE,4,10) =@sysdate))
      end


      set      @idd = rtrim(convert(char,convert(int,@idd)+1))
      set      @bill_no_selfd =@INOUTFlag+'-'+@sysdate+'-'+substring('0000',1,4-len(@idd))+@idd
end


end
















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG


















--------------------------------------------------------------------

CREATE PROCEDURE GET_CURR_YYYYMM_FlagPost  
AS                 
declare @YYYYMM varchar(6)                   --会计年月     

declare @MINBILLDATE DATEtime
declare @MAXBILLDATE DATEtime
declare @PRODUCTDATE DATEtime
declare @B_ID INTEGER
declare @STOREHSFS   INTEGER

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           


   declare  @PREV_YYYYMM          varchar(6)  -- 上一个会计年月
   declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
	if substring(@YYYYMM,5,2) = '12'  --- 如果当前会计月等于最大的会计月，将需要转入下年的的第一个会计年月
	begin
	    set @Next_YYYYMM   = convert(varchar,convert(int,substring(@YYYYMM,1,4))+1) +'01'  
	end
	else
	begin
	    set @Next_YYYYMM   = substring(@YYYYMM,1,4) +substring('00',1,2-len(convert(varchar,convert(int,substring(@YYYYMM,5,2))+1)))+convert(varchar,convert(int,substring(@YYYYMM,5,2))+1)
	end

	if substring(@YYYYMM,5,2) = '01'  --- 如果当前会计月等于最大的会计月，将需要转入下年的的第一个会计年月
	begin
	    set @PREV_YYYYMM   = convert(varchar,convert(int,substring(@YYYYMM,1,4))-1) +'12'  
	end
	else
	begin
	    set @PREV_YYYYMM   = substring(@YYYYMM,1,4) +substring('00',1,2-len(convert(varchar,convert(int,substring(@YYYYMM,5,2))-1)))+convert(varchar,convert(int,substring(@YYYYMM,5,2))-1)
	end

	declare @YYYYMMFS INTEGER
	declare @YYYYMMFSDATE  INTEGER
	declare @Billday  INTEGER

	       SELECT    @YYYYMMFS =(SELECT  YYYYMMFS   FROM   ACCINFO    WHERE   GUID='0001' )    
                IF @YYYYMMFS=1
	  BEGIN
		     SET  @MINBillDate = CONVERT(DATEtime,@YYYYMM+'01')
		     SET  @MAXBillDate =CONVERT(DATEtime,@Next_YYYYMM+'01')

	  END
               ELSE
               BEGIN
	       SELECT    @YYYYMMFSDATE =(SELECT  YYYYMMFSDATE   FROM   ACCINFO    WHERE   GUID='0001' )    
       
	     SET  @MINBillDate =DATEADD(day, @YYYYMMFSDATE, CONVERT(DATEtime,@PREV_YYYYMM+'01'))
	     SET  @MAXBillDate =DATEADD(day, @YYYYMMFSDATE, CONVERT(DATEtime,@YYYYMM+'01'))



	 END

          select DISTINCT CODE ,BILLDATE from VIEWBILL WHERE FLAGPOST = 0  and BILLdate >= @MINBillDate and BILLdate <@MAXBillDate






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG






--------------------------------------------------------------------

---此过程取得单据的标识   ID
---此过程取得单据的标识   ID 为8位字符串

CREATE PROCEDURE [dbo].[GET_CWPZ_BILLID] (@R_KeyValue VARCHAR(20)  output)    --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 
  declare @curKeyValue VARCHAR(20)
  declare @NextKeyValue VARCHAR(20)
  declare @BILLID VARCHAR(20)
  declare @YYYYMM varchar(6)                   --会计年月     

BEGIN
--- 	 set @curkeyvalue='00000000'
          set @YYYYMM   = (select optionvalue from accoptions where optionname ='CW_YYYYMM')     

	  select @curkeyvalue=Substring(BILLID,7,6) from CW_PingZhengM   where Substring(BILLID,1,6)=@YYYYMM

          set @NextKeyValue = rtrim(convert(char,convert(int,@curkeyvalue)+1))
          set @NextKeyValue = substring('000000',1,6-len(@NextKeyValue))+@NextKeyValue

	  if (@curkeyvalue  is NULL)  or (not (len(@curkeyvalue)=6 ) )
	  begin
	    set @R_KeyValue=@YYYYMM+'000001'
	  end
	  else
	  begin
	    set @R_KeyValue =@YYYYMM+@NextKeyValue
	  end
END
  






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG









--------------------------------------------------------------------

---此过程功能试算平衡

CREATE PROCEDURE [dbo].[GET_CW_initbala_PingHeng] (@Debit_LeiJi t_amount  output,@Credit_LeiJi t_amount  output,
        @Balance_Jie t_amount  output,   @YearBalance_Jie t_amount  output,
        @Balance_Dai t_amount  output,   @YearBalance_Dai t_amount  output,
	 @PingHengFlag int   output)
AS 
 
  declare @curKeyValue VARCHAR(20)
  declare @NextKeyValue VARCHAR(20)
  declare @YYYYMM varchar(6)                   --会计年月     
  declare @MAXBILLDATE DATEtime 
  declare @MINBILLDATE DATEtime 
  declare @PLHaveDone_Jie t_amount
  declare @PLHaveDone_Dai t_amount

BEGIN

	set @PingHengFlag=1   ---为平衡

SELECT @Debit_LeiJi=SUM(Debit) ,@Credit_LeiJi=SUM(Credit)  FROM  CW_INITBALA


SELECT @Balance_Jie=SUM(Balance) , @PLHaveDone_Jie=SUM(PLHaveDone)    FROM  CW_INITBALA

where dcflag=1
set @YearBalance_Jie=@Balance_Jie-@Debit_LeiJi+@Credit_LeiJi

SELECT @Balance_Dai=SUM(Balance) , @PLHaveDone_Dai=SUM(PLHaveDone)    FROM  CW_INITBALA

where dcflag=-1

set @YearBalance_Dai=@Balance_Dai-@Debit_LeiJi+@Credit_LeiJi

	if @Debit_LeiJi<>@Credit_LeiJi OR @Balance_Jie<>@Balance_Dai OR @YearBalance_Jie<>@YearBalance_Dai
	begin
	set @PingHengFlag=0   ---不平衡
	end




END
  









----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG







--------------------------------------------------------------------

---此过程取得单据的标识   ID
---此过程取得单据的标识   ID 为8位字符串

CREATE PROCEDURE [dbo].[GET_Cred_Code_NO] (@CredTypeID int ,@CredNo int  output,@CredCode int  output)    --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 
  declare @curKeyValue VARCHAR(20)
  declare @NextKeyValue VARCHAR(20)
  declare @BILLID VARCHAR(20)
  declare @MAXBILLDATE DATEtime 
  declare @MINBILLDATE DATEtime 

BEGIN
--- 	 set @curkeyvalue='00000000'

		exec Get_Max_Min_Date @MAXBILLDATE output,@MINBILLDATE output


	  select @CredNo=Max(CredNo)  from CW_PingZhengM   where BILLDate >=@MINBILLDATE AND BILLDate < @MAXBILLDATE

	  if (@CredNo  is NULL)  
	  begin
	    set @CredNo=1
	  end
	  else
	  begin
	    set @CredNo=@CredNo+1
	  end

	  select @CredCode=Max(CredCode)  from CW_PingZhengM   where BILLDate >=@MINBILLDATE AND BILLDate < @MAXBILLDATE AND CredTypeID=@CredTypeID

	  if (@CredCode  is NULL)  
	  begin
	    set @CredCode=1
	  end
	  else
	  begin
	    set @CredCode=@CredCode+1
	  end






END



----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












----------------------------------------------------------------------------
CREATE PROCEDURE [GET_EPRICE ]  (  @GOODSID varchar(22),      ---单据编号   
	     @STOREID varchar(22),  
	@EPRICE NUMERIC(20,10)   output)     --APSOFTENCRYPTION       WITH ENCRYPTION
AS 


declare @STOREHSFS   INTEGER
declare @MAXID   varchar(30)
declare @MAXbilldate  datetime   
 
BEGIN



	       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )      

                     SELECT   @EPRICE=0.00 

                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN

	                           select @MAXBILLDATE=MAX(BILLDATE) FROM detailbillflow   WHERE  GOODSID=@GOODSID  AND   STOREID=@STOREID    AND YYYYMMBILL=1
	                           SELECT  @MAXID=MAX(ID)  FROM detailbillflow  WHERE  GOODSID=@GOODSID  AND   STOREID=@STOREID   AND  BILLDATE=@MAXBILLDATE    AND YYYYMMBILL=1   
		                 SELECT  @EPRICE =EPRICE    FROM DETAILBILLFLOW  WHERE GOODSID = @GOODSID  AND STOREID=@STOREID  AND ID=@MAXID
                            END
                            IF   @STOREHSFS=0
                            BEGIN
	                            select @MAXBILLDATE=MAX(BILLDATE) FROM detailbillflow   WHERE  GOODSID=@GOODSID     AND YYYYMMBILL=1
	                            SELECT  @MAXID=MAX(ID)  FROM detailbillflow  WHERE  GOODSID=@GOODSID   AND  BILLDATE=@MAXBILLDATE    AND YYYYMMBILL=1   
		                 SELECT  @EPRICE = EPRICE    FROM DETAILBILLFLOW   WHERE GOODSID = @GOODSID  AND ID=@MAXID
                            END

END






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













------------------

CREATE PROCEDURE [dbo].[GET_GoodsTypeNew_PrevNO] (
                  @Lcode varchar(50),
                  @PrevNO varchar(50) output, --单号
                  @ReturnFlag  int output --单号
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --当前会计年月     
declare @idd varchar(50)
declare @HouBuidd varchar(50)                     --序列号
declare @BILLNOFLAG  varchar(1)                     --单据格式
declare @BILLW  varchar(20)                     --单据格式
declare @YYYYMM_FLAG  INTEGER
declare @TempSTR varchar(2000)
declare @MM int

begin

	     Set  @MM= CHARINDEX('.',@LCODE)

	     if @MM=0 
	     begin
	             SET @PrevNO='00' 
	     end	
	     else
	     begin

		     SET @PrevNO=''
		     SET @TempSTR=@Lcode
		     while @MM>0 
		     begin
			 IF @PrevNO=''
			 begin
			 SET @PrevNO=SubString(@TempSTR,1,@MM-1)
			 end
			 ELse
			 begin
			 SET @PrevNO=@PrevNO+'.'+SubString(@TempSTR,1,@MM-1)
			 end
		
		         SET @TempSTR=SubString(@TempSTR,@MM+1,Len(@TempSTR)-@MM)
			 Set @MM= CHARINDEX('.',@TempSTR)

		     end

	     end

             IF exists(select * from GoodstypeNew where LCODE=@PrevNO)
	     begin

		If exists(select * from GoodstypeNew where LCODE=@LCODE)
		begin
		set @ReturnFlag=0
		end
		else
		begin
		set @ReturnFlag=1
		end
	     end
	     else
	     begin
		set @ReturnFlag=0
	     end



end







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












------------------

CREATE PROCEDURE [dbo].[GET_ItemInfo_ItemBM] (
                  @PrevNO varchar(50),
                  @bill_no_selfd varchar(50) output --单号
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --当前会计年月     
declare @idd varchar(50)
declare @HouBuidd varchar(50)                     --序列号
declare @BILLNOFLAG  varchar(1)                     --单据格式
declare @BILLW  varchar(20)                     --单据格式
declare @YYYYMM_FLAG  INTEGER
begin

---      select   @idd = (select max(substring(ItemBM,len(@PrevNO)+1,len(ItemBM)-len(@PrevNO))) as maxid from ItemInfo where PrevNO=@PrevNO)

	if @PrevNO='0000'
	begin
	      set  @bill_no_selfd =''
		return
	end

      select   @idd = (select max(ItemBM) as maxid from ItemInfo where PrevNO=@PrevNO)
--      select   @idd = (select max(substring(CODE,12,4)) as maxid from STOREZZHPM where (len(CODE)=15 and substring(CODE,4,7) =substring(@YYYYMM,1,4)+'-' +substring(@YYYYMM,5,2)))
	set @HouBuIdd='1'+substring(@idd,len(@PrevNO)+1,len(@idd)-len(@PrevNO))

      set      @HouBuIdd = rtrim(convert(char,convert(int,@HouBuIdd)+1))
		
      set      @bill_no_selfd =substring(@HouBuidd,2,len(@HouBuidd)-1)

end






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG















CREATE PROCEDURE GET_MQTY_EQTY_2011(@GOODSID  varchar(20)  ,         ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
					@STOREID varchar(8) ,                        -----如果为0000则全部仓库
						           @MEQTY   NUMERIC(20,10)    OUTPUT,
						           @EQTY   NUMERIC(20,10)    OUTPUT
                         
                                                      )   --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @YYYYMM  varchar(8),      --------为当前会计期间
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000)
Declare    @STOREIDSTR   varchar(80)

set @temp_year  = convert(varchar,year(getdate()))
set @temp_month = substring('00',1,2-len(convert(varchar,month(getdate()))))+convert(varchar,month(getdate()))
set @temp_day   = substring('00',1,2-len(convert(varchar,day(getdate()))))+convert(varchar,day(getdate()))
set @now_date   = @temp_year + @temp_month +@temp_day

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')    

		 IF   @STOREID='0000'
		BEGIN
		 SET @STOREIDSTR = '    '
		END
		ELSE
		BEGIN
		 SET @STOREIDSTR = '  AND   STOREID = '+char(39)+ @STOREID+char(39)
		END
 



----------------------------------------------------
		SELECT @SQLSTR='	INSERT  #GOODSTEMP      select  I.GOODSID,       '
		SELECT @SQLSTR=@SQLSTR+'  ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0)  as MEQTY, '   --期末数量
		SELECT @SQLSTR=@SQLSTR+'  ISNULL(B.BQTY,0)+ isnull(E.INQTY,0)  as EQTY   '   --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from Goods    AS  I'
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(INQTY*INOUTFLAG)  as INQTY  ,sum(MINQTY*INOUTFLAG)  as MINQTY '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)+@STOREIDSTR                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(BQTY) as BQTY ,sum(MBQTY) as MBQTY'
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39)+@STOREIDSTR 
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where    I.GOODSID   = ' +char(39)+@GOODSID+char(39)
------------------------------------------------------------------------
Create Table #GOODSTEMP
      (   GOODSID  nvarchar(50)  NULL,
	[MEQTY] NUMERIC(20,10)  NULL ,
	[EQTY] NUMERIC(20,10)  NULL 
		)

 		EXEC(@SQLSTR)
                      SELECT  @EQTY=(SELECT isnull(EQTY,0)  AS  EQTY  FROM #GOODSTEMP )
                      SELECT  @MEQTY=(SELECT isnull(MEQTY,0)  AS  MEQTY  FROM #GOODSTEMP )









----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













--------------------------------------------------------------------

---此过程解决取五笔和拼音码的首字符

CREATE PROCEDURE [GETwb_py_FIRST] ( @INPUTSTRING   VARCHAR(200) ,  @PY_STRING  VARCHAR(200) output,@WB_STRING  VARCHAR(200)  output)    --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 
  declare @WBTMPSTR  VARCHAR(20)
  declare @PYTMPSTR  VARCHAR(20)
  declare @WBTMPSTR00  VARCHAR(200)
  declare @PYTMPSTR00  VARCHAR(200)
  declare @M  INT

BEGIN
  
	SET @M=LEN(@INPUTSTRING)
	  set @WB_STRING = ''

	  set @PY_STRING = ''

	  set @WBTMPSTR00 = ''

	  set @PYTMPSTR00 = ''

	WHILE @M  > 0
	BEGIN
		  SELECT @WBTMPSTR=SUBSTRING(WB,1,1)  FROM CHINESE  WHERE  SUBSTRING(@INPUTSTRING,@M,1) = HANZI
		  SELECT @PYTMPSTR=SUBSTRING(PY,1,1)  FROM CHINESE  WHERE  SUBSTRING(@INPUTSTRING,@M,1) = HANZI

		  set @WBTMPSTR00 =ISNULL(@WBTMPSTR,'')+@WBTMPSTR00

		  set @PYTMPSTR00 =ISNULL(@PYTMPSTR,'')+@PYTMPSTR00
		                                    
		     SET @M=@M-1
	 END

	  set @WB_STRING = @WBTMPSTR00

	  set @PY_STRING =  @PYTMPSTR00




END






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG







--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE [dbo].[GOODSCGDDMXB]( @WHERESTING   varchar(1800)
                       
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8)

declare @VENDORNAME  varchar(50)
declare @GOODSNAME  varchar(50)

declare @ID  nvarchar(50)
declare @VENDORID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @VENDORCODE  nvarchar(50)
declare @GOODSCODE  nvarchar(50)
declare @SPECNAME nvarchar(50)
declare @MODELNAME nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLCODE  nvarchar(50)
declare @BILLTYPE INT
declare @BILLDATE  datetime
declare @GOODSID00  nvarchar(50)
declare @PRICE NUMERIC(20, 6)
declare @TAXAMT NUMERIC(20, 2)
declare @WCunitQTY NUMERIC(20, 6)
declare @WCquantity NUMERIC(20, 6)
declare @zzunitQTY NUMERIC(20, 6)
declare @zzquantity NUMERIC(20, 6)
declare @WCTAXAMT NUMERIC(20, 6)
declare @TAXRATE  NUMERIC(20, 6)
declare @RATE  NUMERIC(20, 6)
declare @WEITAXAMT NUMERIC(20, 6)
declare @SUMWCTAXAMT NUMERIC(20, 6)
declare @SUMWEITAXAMT NUMERIC(20, 6)
declare @SUMTAXAMT NUMERIC(20, 6)
declare @UNITQTY NUMERIC(20, 6)
declare @quantity NUMERIC(20, 6)
declare @UNITPRICE NUMERIC(20, 6)
declare @DISC NUMERIC(20, 6)
declare    @PRICETYPE int

Create Table #temptable1
      (   GOODSID varchar(50)  NULL,
       VENDORID  varchar(10) ,
       VENDORCODE  varchar(30) ,
      BILLID  nvarchar(50)  NULL,
      BILLTYPE  INT ,
	[PRICE] NUMERIC(20, 6)  NULL ,
	[UNITQTY] NUMERIC(20, 6)  NULL ,
	[quantity] NUMERIC(20, 6)  NULL ,
	[DISC] NUMERIC(20, 6)  NULL ,
	[TAXRATE]NUMERIC(20, 6)  NULL ,
	   BILLDATE  datetime  NULL,
	[UNITPRICE] NUMERIC(20, 6)  NULL ,
	[WCunitQTY]NUMERIC(20, 6)  NULL ,
	[WCquantity]NUMERIC(20, 6)  NULL ,
	[zzunitQTY]NUMERIC(20, 6)  NULL ,
	[zzquantity]NUMERIC(20, 6)  NULL ,
	[TAXAMT]NUMERIC(20, 2)  NULL, 
	[PRICETYPE]    int  NULL, 
	       DETAILBILLFLOWID  varchar(10) 
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   VIEWCGDD.GOODSID,VIEWCGDD.VENDORID,VENDOR.CODE AS VENDORCODE, BILLID,BILLTYPE,PRICE,UNITQTY,quantity,DISC,TAXRATE,BILLDATE '
           SELECT  @SQLSTR = @SQLSTR+' ,UNITPRICE,WCunitQTY,WCquantity,zzunitQTY,zzquantity,TAXAMT,PRICETYPE,DETAILBILLFLOWID  from VIEWCGDD   ,VENDOR  '  + @WHERESTING +'  AND  VIEWCGDD.VENDORID = VENDOR.VENDORID'
           SELECT  @SQLSTR = @SQLSTR+'  order by VIEWCGDD.GOODSID,VIEWCGDD.VENDORID,BILLDATE,DETAILBILLFLOWID '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
	   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   VENDORNAME  nvarchar(50)  NULL,
   VENDORCODE  nvarchar(50)  NULL,
   UNIT  nvarchar(10)  NULL,
	[UNITQTY] NUMERIC(20, 6)  NULL ,
	[quantity] NUMERIC(20, 6)  NULL ,
	[TAXAMT]NUMERIC(20, 2)  NULL, 
	[WCunitQTY] NUMERIC(20, 6)  NULL ,
	[WCquantity] NUMERIC(20, 6)  NULL ,
	[zzunitQTY] NUMERIC(20, 6)  NULL ,
	[zzquantity] NUMERIC(20, 6)  NULL ,
	[WCTAXAMT]NUMERIC(20, 6)  NULL ,
	[WEIunitQTY] NUMERIC(20, 6)  NULL ,
	[WEIquantity] NUMERIC(20, 6)  NULL ,
	[WEITAXAMT]NUMERIC(20, 6)  NULL 
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (select  GOODSID, VENDORID, BILLID,PRICE,UNITQTY,TAXRATE,BILLTYPE   from  #temptable1        )
                 begin
	    declare CGDDMXB_GOODS Cursor for select  GOODSID, VENDORID, BILLID,PRICE,UNITQTY,quantity,TAXRATE,BILLTYPE ,DISC,UNITPRICE,WCunitQTY,WCquantity, zzunitQTY,zzquantity,TAXAMT,PRICETYPE  from  #temptable1  
---                                                            ORDER BY  GOODSID,  BILLDATE,DETAILBILLFLOWID,VENDORCODE
                                                            ORDER BY  GOODSID,  BILLDATE,BILLID,VENDORCODE
	    Open CGDDMXB_GOODS

	    fetch CGDDMXB_GOODS into   @GOODSID,@VENDORID,@BILLID,@PRICE,@UNITQTY,@quantity,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@WCunitQTY,@WCquantity,@zzunitQTY,@zzquantity,@TAXAMT,@PRICETYPE

                 SELECT  @VENDORNAME =(SELECT NAME   FROM VENDOR  WHERE VENDORID=@VENDORID)
                 SELECT  @VENDORCODE =(SELECT CODE  FROM VENDOR  WHERE VENDORID=@VENDORID)
                 SELECT  @GOODSCODE=CODE,@GOODSNAME=Name,@SpecName=SpecName,@ModelName=ModelName     FROM GOODS  WHERE GOODSID=@GOODSID
                 SELECT  @GOODSNAME =@GOODSNAME+' '+ISNULL(@SpecName,'')+' '+ISNULL(@ModelName,'')
                 SELECT  @GOODSCODE='钢材编码：'+@GOODSCODE

                 SELECT  @GOODSID00=@GOODSID

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,VENDORNAME         )
                                           VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
		SELECT @SUMWCTAXAMT=0
		SELECT @SUMTAXAMT=0
		SELECT @SUMWEITAXAMT=0
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF  not( @GOODSID00 = @GOODSID)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,WCTAXAMT,TAXAMT,WEITAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMWCTAXAMT,@SUMTAXAMT,@SUMWEITAXAMT)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

		                 SELECT  @VENDORNAME =(SELECT NAME   FROM VENDOR  WHERE VENDORID=@VENDORID)
		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @VENDORCODE =(SELECT CODE  FROM VENDOR  WHERE VENDORID=@VENDORID)
                 SELECT  @GOODSCODE=CODE,@GOODSNAME=Name,@SpecName=SpecName,@ModelName=ModelName     FROM GOODS  WHERE GOODSID=@GOODSID
                 SELECT  @GOODSNAME =@GOODSNAME+' '+ISNULL(@SpecName,'')+' '+ISNULL(@ModelName,'')
                 SELECT  @GOODSCODE='钢材编码：'+@GOODSCODE
		                 
		                 SELECT  @GOODSID00=@GOODSID


			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,VENDORNAME         )
                                           VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
				SELECT @SUMWCTAXAMT=0
				SELECT @SUMTAXAMT=0
				SELECT @SUMWEITAXAMT=0
		END	
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

				--SELECT @RATE =RATE  FROM VENDORUNIT  WHERE VENDORID=@VENDORID AND UNITID=@UNITID

			SELECT @UNIT = UNIT   FROM GOODS  WHERE GOODSID=@GOODSID
				
			   SELECT @BILLCODE=(SELECT CODE   FROM STORECGDDM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STORECGDDM  WHERE BILLID=@BILLID)
		                 SELECT  @VENDORNAME=(SELECT NAME   FROM VENDOR  WHERE VENDORID=@VENDORID)
		                 SELECT  @VENDORCODE=(SELECT CODE   FROM VENDOR  WHERE VENDORID=@VENDORID)
		               if @PRICETYPE=1
		               begin  
		                 SET @WEITAXAMT=Round(ISNULL(@DISC,100)*0.01*(ISNULL(@quantity,0)-ISNULL(@WCquantity,0)-ISNULL(@zzquantity,0))*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
		                 SET @WCTAXAMT=Round(ISNULL(@DISC,100)*0.01*ISNULL(@WCquantity,0)*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
					   end
					   else
					   begin
		                 SET @WEITAXAMT=Round(ISNULL(@DISC,100)*0.01*(ISNULL(@unitqty,0)-ISNULL(@WCunitqty,0)-ISNULL(@zzunitqty,0))*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
		                 SET @WCTAXAMT=Round(ISNULL(@DISC,100)*0.01*ISNULL(@WCunitqty,0)*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
					   end
		                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,VENDORNAME,VENDORCODE,UNIT, UNITQTY,quantity,TAXAMT,WCunitQTY,WCquantity,zzunitQTY,zzquantity,WCTAXAMT,WEIunitQTY,WEIquantity,WEITAXAMT)
             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@VENDORNAME,@VENDORCODE,@UNIT,@UNITQTY,@quantity,
					                     @TAXAMT,
					                     ISNULL(@WCunitQTY,0) ,
					                     ISNULL(@WCquantity,0) ,
					                     ISNULL(@zzunitQTY,0) ,
					                     ISNULL(@zzquantity,0) ,					@WCTAXAMT,
					                      @UNITQTY-ISNULL(@WCunitQTY,0) -ISNULL(@zzunitQTY,0),
					                      @quantity-ISNULL(@WCquantity,0) -ISNULL(@zzquantity,0),@WEITAXAMT	)

				SELECT @SUMTAXAMT=@SUMTAXAMT+@TAXAMT
				SELECT @SUMWCTAXAMT=@SUMWCTAXAMT+@WCTAXAMT
				SELECT @SUMWEITAXAMT=@SUMWEITAXAMT+@WEITAXAMT
		
	    fetch CGDDMXB_GOODS into   @GOODSID,@VENDORID,@BILLID,@PRICE,@UNITQTY,@quantity,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@WCunitQTY,@WCquantity,@zzunitQTY,@zzquantity,@TAXAMT,@PRICETYPE
 
	    END           ------- CGDDMXB_GOODS  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,WCTAXAMT,TAXAMT,WEITAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMWCTAXAMT,@SUMTAXAMT,@SUMWEITAXAMT)

	    close CGDDMXB_GOODS
	    deallocate CGDDMXB_GOODS
        end     ------------  if exists

 SELECT *  FROM #temptable2         ORDER BY ID












----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG


















--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE GOODSCGRKMXB( @WHERESTING   varchar(1800)
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8)

declare @VENDORNAME  varchar(50)

declare @ID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @VENDORID  nvarchar(50)
declare @GOODSNAME  nvarchar(50)
declare @GOODSCODE  nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLTYPE  INT
declare @PRICETYPE  INT
declare @BILLCODE  nvarchar(50)
declare @BILLDATE  datetime
declare @GOODSID00  nvarchar(50)
declare @PRICE NUMERIC(20,10)
declare @QUANTITY NUMERIC(20,10)
declare @TAXRATE  NUMERIC(20,10)
declare @SUMAMT NUMERIC(20,10)
declare @UNITPRICE  NUMERIC(20,10)
declare @UNITQTY NUMERIC(20,10)
declare @FuZhuQTY varchar(50)
declare @DISC NUMERIC(20,10)
declare @SUMTAXAMT NUMERIC(20,10)
declare @AMT NUMERIC(20,10)
declare @TAXAMT NUMERIC(20,10)
declare @VendorFlag smallint 
declare @DunQTY NUMERIC(20,10)
declare @Rate NUMERIC(20,10)
declare @SumDunQTY NUMERIC(20,10)
    

Create Table #temptable1
      (GOODSID  varchar(10) ,
             goodscode  nvarchar(50)  NULL,
             BILLID  nvarchar(50)  NULL,
             BILLTYPE  INT,
	[PRICE] NUMERIC(20,10)  NULL ,
	[QUANTITY] NUMERIC(20,10)  NULL ,
	[TAXRATE]NUMERIC(20,10)  NULL ,
	[DISC]NUMERIC(20,10)  NULL ,
	BILLDATE DATEtime,
	[UNITPRICE] NUMERIC(20,10)  NULL ,
	[UNITQTY]NUMERIC(20,10)  NULL ,
	FuZhuQTY varchar(50)  NULL,
		     PRICETYPE  INT ,
	[AMT]NUMERIC(20,10)  NULL ,
	[TAXAMT]NUMERIC(20,10)  NULL, 
	[VendorFlag]smallint  NULL 
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   VIEWCGRK.GOODSID,GOODS.CODE AS GOODSCODE, BILLID,BILLTYPE,VIEWCGRK.PRICE,QUANTITY,TAXRATE,DISC,BILLDATE '
           SELECT  @SQLSTR = @SQLSTR+' , UNITPRICE ,UNITQTY,FuZhuQTY,PRICETYPE,AMT,TAXAMT,VendorFlag  from VIEWCGRK   ,GOODS    '  + @WHERESTING +'  AND  VIEWCGRK.GOODSID = GOODS.GOODSID'
           SELECT  @SQLSTR = @SQLSTR+'  order by  VIEWCGRK.GOODSID,BILLDATE,BILLID '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   VENDORNAME  nvarchar(50)  NULL,
   UNIT  nvarchar(10)  NULL,
	[QUANTITY] NUMERIC(20,10)  NULL ,
	[PRICE] NUMERIC(20,10)  NULL ,
	[TAXRATE]NUMERIC(20,10)  NULL ,
	[AMT]NUMERIC(20,10)  NULL ,
	[TAXAMT]NUMERIC(20,10)  NULL ,
	 PRICETYPENAME  nvarchar(10)  NULL,
	FuZhuQTY varchar(50)  NULL,
	[DunQTY]NUMERIC(20,10)  NULL 
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (select   GOODSID, BILLID,PRICE,QUANTITY,TAXRATE   from  #temptable1        )
                 begin
	    declare CGRKMXB_CRGR Cursor for select   GOODSID, BILLID,PRICE,QUANTITY,FuZhuQTY,TAXRATE,BILLTYPE,DISC,UNITPRICE ,UNITQTY ,PRICETYPE,AMT,TAXAMT,VendorFlag  from  #temptable1  
                                                            ORDER BY  GOODSID,BILLDATE, BILLID
	    Open CGRKMXB_CRGR

	    fetch CGRKMXB_CRGR into   @GOODSID,@BILLID,@PRICE,@QUANTITY,@FuZhuQTY,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE ,@UNITQTY  ,@PRICETYPE, @AMT,@TAXAMT,@VendorFlag

                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @GOODSCODE='商品编码：'+@GOODSCODE
                 SELECT  @GOODSID00=@GOODSID

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,VENDORNAME         )
                                           VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
		SELECT @SUMAMT=0
		SELECT @SUMTAXAMT=0
		SELECT @SUMDunQTY=0
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF  not( @GOODSID00 = @GOODSID)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,AMT,TAXAMT,DunQTY)
                                           VALUES  (@COUNTID, '小计',@SUMAMT,@SUMTAXAMT,@SumDunQTY)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @GOODSCODE='商品编码：'+@GOODSCODE
		                 SELECT  @GOODSID00=@GOODSID

			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                          INSERT    INTO   #temptable2  (ID, BILLCODE,VENDORNAME    )
                           	                VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
				SELECT @SUMAMT=0
				SELECT @SUMTAXAMT=0
				SELECT @SUMDunQTY=0
		END	
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	  			SELECT @UNIT = (SELECT UNIT   FROM GOODS  WHERE GOODSID=@GOODSID)

			   IF @BILLTYPE=1
			  BEGIN
			   SELECT @BILLCODE=(SELECT CODE   FROM STORECGRKM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STORECGRKM  WHERE BILLID=@BILLID)
			   SELECT @VENDORID=(SELECT VENDORID   FROM STORECGRKM  WHERE BILLID=@BILLID)
			  END
			   IF @BILLTYPE=7
			  BEGIN
			   SELECT @BILLCODE=(SELECT CODE   FROM STORECGTHM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STORECGTHM  WHERE BILLID=@BILLID)
			   SELECT @VENDORID=(SELECT VENDORID   FROM STORECGTHM  WHERE BILLID=@BILLID)
			  END
		                 SELECT  @VENDORNAME =(SELECT NAME   FROM ViewVENDOR  WHERE VENDORID=@VENDORID  and VendorFlag=@VendorFlag)

				IF @PRICETYPE=1 
				BEGIN
			                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,VENDORNAME,UNIT, QUANTITY,FuZhuQTY,PRICE,TAXRATE, AMT,TAXAMT,PRICETYPENAME,DunQTY)
             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@VENDORNAME,@UNIT,@UNITQTY,@FuZhuQTY,@UNITPRICE,@TAXRATE,@AMT,@TAXAMT,'重量',@QUANTITY)
					
					set @DunQTY=@QUANTITY
				END
				IF @PRICETYPE=0
				BEGIN
		                 SELECT  @Rate =(SELECT ISNULL(Rate,0)*0.001 FROM GOODS  WHERE GOODSID=@GOODSID)

			                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,VENDORNAME,UNIT, QUANTITY,FuZhuQTY,PRICE,TAXRATE, AMT,TAXAMT,PRICETYPENAME,DunQTY)
             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@VENDORNAME,@UNIT,@UNITQTY,@FuZhuQTY,@UNITPRICE,@TAXRATE,@AMT,@TAXAMT,'数量',@Rate*@UNITQTY)
					set @DunQTY=@Rate*@UNITQTY
				END

				SELECT @SUMAMT=@SUMAMT+@AMT
				SELECT @SUMTAXAMT=@SUMTAXAMT+@TAXAMT
				SELECT @SUMDunQTY=@SUMDunQTY+@DunQTY
		
	    fetch CGRKMXB_CRGR into   @GOODSID,@BILLID,@PRICE,@QUANTITY,@FuZhuQTY,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE ,@UNITQTY  ,@PRICETYPE, @AMT,@TAXAMT,@VendorFlag
 
	    END           ------- CGRKMXB_CRGR  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,AMT,TAXAMT,DunQTY)
                                           VALUES  (@COUNTID, '小计',@SUMAMT,@SUMTAXAMT,@SUMDunQTY)

	    close CGRKMXB_CRGR
	    deallocate CGRKMXB_CRGR
        end     ------------  if exists

 SELECT *  FROM #temptable2         ORDER BY ID









----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG









------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE GOODSGJRKMXB( 
				@BEGINDATE   varchar(18),
				@ENDDATE   varchar(18),
				@WHERESTING   varchar(1800)
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8)

declare @VENDORNAME  varchar(50)

declare @ID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @VENDORID  nvarchar(50)
declare @GOODSNAME  nvarchar(50)
declare @GOODSCODE  nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLTYPE  INT
declare @BILLCODE  nvarchar(50)
declare @BILLDATE  datetime
declare @GOODSID00  nvarchar(50)
declare @PRICE NUMERIC(20,10)
declare @QTY NUMERIC(20,10)
declare @AMT NUMERIC(20,10)
declare @QUANTITY NUMERIC(20,10)
declare @SUMAMT NUMERIC(20,10)
declare @UNITPRICE  NUMERIC(20,10)
declare @UNITQTY NUMERIC(20,10)
declare @SUMQTY NUMERIC(20,10)
    

Create Table #temptable1
      (GOODSID  varchar(10) ,
             goodscode  nvarchar(50)  NULL,
             BILLID  nvarchar(50)  NULL,
             BILLTYPE  INT,
	[PRICE] NUMERIC(20,10)  NULL ,
	[QUANTITY] NUMERIC(20,10)  NULL ,
	[TAXRATE]NUMERIC(20,10)  NULL ,
	[DISC]NUMERIC(20,10)  NULL ,
	BILLDATE DATEtime,
	[UNITPRICE] NUMERIC(20,10)  NULL ,
	[UNITQTY]NUMERIC(20,10)  NULL 
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   VIEWGJRK.GOODSID,GOODS.CODE AS GOODSCODE, BILLID,BILLTYPE,VIEWGJRK.PRICE,QUANTITY,TAXRATE,DISC,BILLDATE '
           SELECT  @SQLSTR = @SQLSTR+' , UNITPRICE ,UNITQTY   from VIEWGJRK   ,GOODS    '  + @WHERESTING +'  AND  VIEWGJRK.GOODSID = GOODS.GOODSID '
           SELECT  @SQLSTR = @SQLSTR+'   AND   BILLDATE <= '+CHAR(39)+@ENDDATE +CHAR(39) +' AND   BILLDATE >= '+CHAR(39)+@BEGINDATE+CHAR(39)
           SELECT  @SQLSTR = @SQLSTR+'   order by  VIEWGJRK.GOODSID,BILLDATE,BILLID '  
            EXEC( @SQLSTR)

Create Table #temptable10
      (GOODSID  varchar(10) ,
	[QTY] NUMERIC(20,10)  NULL ,
	[AMT] NUMERIC(20,10)  NULL 
		)

-----------------------------------------这个地方应该为合计数

           SELECT  @SQLSTR = ' INSERT #temptable10  '
           SELECT  @SQLSTR = @SQLSTR+' select   VIEWGJRK.GOODSID, SUM(ISNULL(QUANTITY,0))  AS QTY '
           SELECT  @SQLSTR = @SQLSTR+' , SUM(UNITPRICE*(isnull(quantity,0)-ISNULL(RETURNQTY,0)))  AS AMT      from VIEWGJRK   ,GOODS    '  + @WHERESTING +'  AND  VIEWGJRK.GOODSID = GOODS.GOODSID'
           SELECT  @SQLSTR = @SQLSTR+ ' AND   BILLDATE < '+CHAR(39)+@BEGINDATE +CHAR(39)+'     AND   VIEWGJRK.GOODSID NOT IN (SELECT GOODSID FROM  #temptable1  )   '
           SELECT  @SQLSTR = @SQLSTR+ ' AND   QUANTITY > 0   AND  ( QUANTITY-ISNULL(RETURNQTY,0)) > 0 '
           SELECT  @SQLSTR = @SQLSTR+'  GROUP  BY  VIEWGJRK.GOODSID   '  
           SELECT  @SQLSTR = @SQLSTR+'  order by  VIEWGJRK.GOODSID  '  
            EXEC( @SQLSTR)

Create Table #temptable2
      (ID  varchar(10) primary key,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   VENDORNAME  nvarchar(50)  NULL,
   UNIT  nvarchar(10)  NULL,
	[GRQTY] NUMERIC(20,10)  NULL ,
	[GRAMT] NUMERIC(20,10)  NULL ,
	[CHQTY]NUMERIC(20,10)  NULL ,
	[CHAMT]NUMERIC(20,10)  NULL ,
	[EQTY]NUMERIC(20,10)  NULL ,
	[EAMT]NUMERIC(20,10)  NULL 
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (select   GOODSID, BILLID,PRICE,QUANTITY,TAXRATE   from  #temptable1        )
                 begin
	    declare GJRKMXB_CRGR Cursor for select   GOODSID, BILLID,PRICE,QUANTITY,BILLTYPE,UNITPRICE ,UNITQTY   from  #temptable1  
                                                            ORDER BY  GOODSID,BILLDATE, BILLID
	    Open GJRKMXB_CRGR

	    fetch GJRKMXB_CRGR into   @GOODSID,@BILLID,@PRICE,@QUANTITY,@BILLTYPE,@UNITPRICE ,@UNITQTY  

                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @GOODSCODE='商品编码：'+@GOODSCODE
                 SELECT  @GOODSID00=@GOODSID

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,VENDORNAME         )
                                           VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
		SELECT @SUMAMT=isnull(SUM(QUANTITY*UNITPRICE),0)  FROM  VIEWGJRK  WHERE BILLDATE  < @BEGINDATE  AND GOODSID=@GOODSID
		SELECT @SUMQTY=isnull(SUM(QUANTITY),0)  FROM  VIEWGJRK  WHERE BILLDATE  < @BEGINDATE  AND GOODSID=@GOODSID

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,EAMT,EQTY)
                                           VALUES  (@COUNTID, '期     初',@SUMAMT,@SUMQTY)
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF  not( @GOODSID00 = @GOODSID)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,EAMT,EQTY)
                                           VALUES  (@COUNTID, '期     末',@SUMAMT,@SUMQTY)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @GOODSCODE='商品编码：'+@GOODSCODE
		                 SELECT  @GOODSID00=@GOODSID

			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                          INSERT    INTO   #temptable2  (ID, BILLCODE,VENDORNAME    )
                           	                VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
				SELECT @SUMAMT=isnull(SUM(QUANTITY*UNITPRICE),0)  FROM  VIEWGJRK  WHERE BILLDATE  < @BEGINDATE  AND GOODSID=@GOODSID
				SELECT @SUMQTY=isnull(SUM(QUANTITY),0)  FROM  VIEWGJRK  WHERE BILLDATE  < @BEGINDATE  AND GOODSID=@GOODSID

			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

			                          INSERT    INTO   #temptable2  (ID, BILLCODE,EAMT,EQTY)
                          		                 VALUES  (@COUNTID, '期     初',@SUMAMT,@SUMQTY)

		END	
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	  			SELECT @UNIT = (SELECT UNIT   FROM GOODS  WHERE GOODSID=@GOODSID)

			   SELECT @BILLCODE=(SELECT CODE   FROM STOREGJRKM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STOREGJRKM  WHERE BILLID=@BILLID)
			   SELECT @VENDORID=(SELECT VENDORID   FROM STOREGJRKM  WHERE BILLID=@BILLID)

		                 SELECT  @VENDORNAME=(SELECT NAME   FROM VENDOR  WHERE VENDORID=@VENDORID)

				SELECT @SUMAMT=@SUMAMT+ROUND(@QUANTITY*@UNITPRICE,2)
				SELECT @SUMQTY=@SUMQTY+isnull(@QUANTITY,0)
					IF @QUANTITY>0   
					BEGIN
			                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,VENDORNAME,UNIT, GRQTY,GRAMT,EQTY,EAMT)
             			                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@VENDORNAME,@UNIT,@QUANTITY,
					ROUND(@QUANTITY*@UNITPRICE,2),@SUMQTY,@SUMAMT)
					END
					IF @QUANTITY<0   
					BEGIN
			                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,VENDORNAME,UNIT, CHQTY,CHAMT,EQTY,EAMT)
	             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@VENDORNAME,@UNIT,-@QUANTITY,
					ROUND(-@QUANTITY*@UNITPRICE,2),@SUMQTY,@SUMAMT)
					END
		
	    fetch GJRKMXB_CRGR into   @GOODSID,@BILLID,@PRICE,@QUANTITY,@BILLTYPE,@UNITPRICE ,@UNITQTY  
 
	    END           ------- GJRKMXB_CRGR  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,EAMT,EQTY)
                                           VALUES  (@COUNTID, '期     末',@SUMAMT,@SUMQTY)

	    close GJRKMXB_CRGR
	    deallocate GJRKMXB_CRGR
        end     ------------  if exists

---------------------------------------------------------------------------------------------------相当于处理月结记录
	   if exists (select   GOODSID, QTY,AMT   from  #temptable10        )
                 begin
	    declare GJRKMXB_SEC Cursor for select  GOODSID, QTY,AMT from  #temptable10  
                                                            ORDER BY      GOODSID
	    Open GJRKMXB_SEC

	    fetch GJRKMXB_SEC into   @GOODSID,@SUMQTY,@SUMAMT

	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @GOODSCODE='商品编码：'+@GOODSCODE
                 SELECT  @GOODSID00=@GOODSID

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,VENDORNAME         )
                                           VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,EAMT,EQTY)
                                           VALUES  (@COUNTID, '期     初',@SUMAMT,@SUMQTY)

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,EAMT,EQTY)
                                           VALUES  (@COUNTID, '期     末',@SUMAMT,@SUMQTY)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

	
	    fetch GJRKMXB_SEC into   @GOODSID,@SUMQTY,@SUMAMT
 
	    END           ------- GJRKMXB_SEC  WHILE

	    close GJRKMXB_SEC
	    deallocate GJRKMXB_SEC
        end     ------------  if exists

 SELECT *  FROM #temptable2         ORDER BY ID





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG










--------------------------------------------------------------------
--------------------------------------------------------------------

CREATE PROCEDURE GOODSGJRKYYYYMMDD(@STOREID varchar(8) ,                        -----如果为0000则全部仓库
                                                                                            @Begin_Date   varchar(10) ,
                                                                                           @End_date   varchar(10) ,  
						           @LCODE  varchar(10),             ---如果LCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSCODE  varchar(20),             ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSNAME  varchar(20),             ---如果GOODSNAME  为‘GGGG’表示不对类别进行查询
                                                                                           @INF_COSTINGTYPEID   smallint      --------同价调拨标志   0  代表 不作为过滤条件

                         
                                                      )     --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @WHERESTING   varchar(1800),
        @STOREIDSTR   varchar(100)

                   set @now_date=(select   max(billDATE)   FROM VIEWGJRK)
		
		IF @now_date IS NULL
		BEGIN
			SET @now_date='2030-12-12'
		END

--@WHERESTR='  and 1=1 '
		if     NOT (@LCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = '  AND   I.GOODSID IN ( select G.GOODSID from GoodsTypetree T, GOODS G where T.indirect_no = '+CHAR(39)+@LCODE+CHAR(39)+ '  AND T.self_no=G.LCODE )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  ='     '
 		END
		if     NOT (@GOODSCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  CODE LIKE   '+CHAR(39)+'%'+@GOODSCODE+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  =@WHERESTING+'     '
 		END
		if     NOT (@GOODSNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  NAME LIKE   '+CHAR(39)+'%'+@GOODSNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END
		if     NOT (@INF_COSTINGTYPEID=0)
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where INF_COSTINGTYPEID =  '+str(@INF_COSTINGTYPEID)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END
		if     NOT (@STOREID='0000')
                           BEGIN
	                           SELECT    @STOREIDSTR   = '    AND   STOREID =  '+CHAR(39)+@STOREID +CHAR(39)
                           END
                           ELSE
                           BEGIN
			SELECT    @STOREIDSTR   = '     '
 		END

----------------------------------------------------
		SELECT @SQLSTR='	 select  I.GOODSID,       '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)   as BQTY, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)   as BAMOUNT, ' --期初金额
		SELECT @SQLSTR=@SQLSTR+'ISNULL(BE.INQTY,0)  AS INQTY   ,-ISNULL(BE00.INQTY,0)  AS OUTQTY,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(BE.INAMOUNT,0)  AS INAMOUNT  ,-ISNULL(BE00.INAMOUNT,0)  AS OUTAMOUNT,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0) '
		SELECT @SQLSTR=@SQLSTR+'+ isnull(BE.INQTY,0)+isnull(BE00.INQTY,0) as EQTY ,' --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)  '
                           SELECT @SQLSTR=@SQLSTR+'+ISNULL(BE.INAMOUNT,0)+ISNULL(BE00.INAMOUNT,0)       as EAMOUNT '--期初金额
		 SELECT @SQLSTR=@SQLSTR+' from Goods  AS  I  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(QUANTITY) as BQTY ,SUM(ROUND(QUANTITY*unitPRICE,2))  AS BAMOUNT'
		 SELECT @SQLSTR=@SQLSTR+' from VIEWGJRK  '
		SELECT @SQLSTR=@SQLSTR+'  where    BILLDATE < '+char(39)+@begin_date+char(39) +@STOREIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(QUANTITY) as INQTY  ,sum(ROUND(QUANTITY*UNITPRICE,2))  as INAMOUNT      '
		 SELECT @SQLSTR=@SQLSTR+' from VIEWGJRK  '
		SELECT @SQLSTR=@SQLSTR+' where  QUANTITY > 0  AND BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+@End_Date+char(39) +@STOREIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE on BE.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(QUANTITY) as INQTY  ,sum(ROUND(QUANTITY*UNITPRICE,2))  as INAMOUNT      '
		 SELECT @SQLSTR=@SQLSTR+' from VIEWGJRK  '
		SELECT @SQLSTR=@SQLSTR+' where   QUANTITY < 0  AND BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+@End_Date+char(39)+@STOREIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE00 on BE00.GOODSID = I.GOODSID  '
                          SELECT @SQLSTR=@SQLSTR+'  where     I. GOODSID in (select GOODSID from  VIEWGJRK   where    BILLDATE <='+char(39)+@End_Date+char(39)+@STOREIDSTR+')'  + @WHERESTING 
		SELECT @SQLSTR=@SQLSTR+'          order by  I.CODE                '   
------------------------------------------------------------------------
		EXEC(@SQLSTR)





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













--------------------------------------------------------------------

CREATE PROCEDURE GOODSNAME_CF (
                              @GOODSID   varchar(60),   --产品ID
                              @GOODSNAME   varchar(60),   --产品名称 
                              @SPECNAME            varchar(60)     ,      ---产品规格
                              @ISHAVEFLAG         int output     ---没有重复  -- 0 有重复  --1 
                            )  --APSOFTENCRYPTION       WITH ENCRYPTION
 AS 

  if  len(@SPECNAME)=0
  BEGIN
	  if exists (SELECT GOODSID   FROM GOODS  WHERE (GOODSID<>@GOODSID)  AND (SPECNAME  IS NULL)  AND NAME=@GOODSNAME)
	  BEGIN
		SET @ISHAVEFLAG =1
	  END
	  ELSE
	  BEGIN
		SET @ISHAVEFLAG =0
	  END
  END
  ELSE
  BEGIN
	  if exists (SELECT GOODSID   FROM GOODS  WHERE  (GOODSID<>@GOODSID) AND  SPECNAME=@SPECNAME  AND NAME=@GOODSNAME)
	  BEGIN
		SET @ISHAVEFLAG =1
	  END
	  ELSE
	  BEGIN
		SET @ISHAVEFLAG =0
	  END
  END







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE GOODSXSCKMLRMXB( @WHERESTING   varchar(1800)
                       
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8)

declare @CLIENTNAME  varchar(50)

declare @ID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @BILLTYPE  INT
declare @CLIENTID  nvarchar(50)
declare @GOODSNAME  nvarchar(50)
declare @GOODSCODE  nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLCODE  nvarchar(50)
declare @BILLDATE  datetime
declare @GOODSID00  nvarchar(50)
declare @PRICE NUMERIC(20,10)
declare @QUANTITY NUMERIC(20,10)
declare @TAXRATE  NUMERIC(20,10)
declare @SUMAMT NUMERIC(20,10)
declare @APRICE NUMERIC(20,10)
declare @DISC NUMERIC(20,10)
declare @SUMXSCBAMT NUMERIC(20,10)
declare @AMT NUMERIC(20,10)
declare @ClientFlag smallint 
    

Create Table #temptable1
      (GOODSID  varchar(10) ,
             GOODSCODE  nvarchar(50)  NULL,
             BILLID  nvarchar(50)  NULL,
             BILLTYPE  INT,
	[UNITPRICE] NUMERIC(20,10)  NULL ,
	[APRICE] NUMERIC(20,10)  NULL ,
	[DISC] NUMERIC(20,10)  NULL ,
	[QUANTITY] NUMERIC(20,10)  NULL ,
	[TAXRATE]NUMERIC(20,10)  NULL ,
	BILLDATE DATEtime,
	AMT NUMERIC(20,10)  NULL ,
	[ClientFlag]smallint  NULL 
	)



           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select    VIEWXSCK_2011.GOODSID,GOODS.CODE AS GOODSCODE, BILLID,BILLTYPE,UNITPRICE, VIEWXSCK_2011.APRICE,DISC,QUANTITY,TAXRATE ,BILLDATE, AMT ,ClientFlag '
           SELECT  @SQLSTR = @SQLSTR+'  from VIEWXSCK_2011   ,GOODS  '  + @WHERESTING +'  AND  VIEWXSCK_2011.GOODSID = GOODS.GOODSID'
           SELECT  @SQLSTR = @SQLSTR+'  order by VIEWXSCK_2011.GOODSID,BILLDATE,BILLID '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   CLIENTNAME  nvarchar(50)  NULL,
   UNIT  nvarchar(10)  NULL,
	[QUANTITY] NUMERIC(20,10)  NULL ,
	[PRICE] NUMERIC(20,10)  NULL ,
	[APRICE] NUMERIC(20,10)  NULL ,
	[TAXRATE]NUMERIC(20,10)  NULL ,
	[AMT]NUMERIC(20,10)  NULL ,  ------销售收入
	[XSCBAMT]NUMERIC(20,10)  NULL, ----销售成本
	[MLRAMT]NUMERIC(20,10)  NULL, ----销售成本
	[MLV]NUMERIC(20,10)  NULL ----销售成本
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (select   GOODSID, BILLID,UNITPRICE,APRICE,DISC,QUANTITY,TAXRATE   from  #temptable1        )
                 begin
	    declare XSCKMLRMXB_XSCK Cursor for select   GOODSID, BILLID,UNITPRICE,APRICE,DISC,QUANTITY,TAXRATE,BILLTYPE,AMT,ClientFlag   from  #temptable1  
                                                            ORDER BY  GOODSCODE, BILLDATE,BILLID
	    Open XSCKMLRMXB_XSCK

	    fetch XSCKMLRMXB_XSCK into   @GOODSID,@BILLID,@PRICE,@APRICE,@DISC,@QUANTITY,@TAXRATE,@BILLTYPE,@AMT,@ClientFlag

                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @GOODSCODE='商品编码：'+@GOODSCODE
                 SELECT  @GOODSID00=@GOODSID

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,CLIENTNAME         )
                                           VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
		SELECT @SUMAMT=0
		SELECT @SUMXSCBAMT=0
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF  not( @GOODSID00 = @GOODSID)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,AMT,XSCBAMT)
                                           VALUES  (@COUNTID, '小计',@SUMAMT,@SUMXSCBAMT)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @GOODSCODE='商品编码：'+@GOODSCODE
		                 SELECT  @GOODSID00=@GOODSID

			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                          INSERT    INTO   #temptable2  (ID, BILLCODE,CLIENTNAME    )
                           	                VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
				SELECT @SUMAMT=0
				SELECT @SUMXSCBAMT=0
		END	
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
	  			SELECT @UNIT = (SELECT UNIT   FROM GOODS  WHERE GOODSID=@GOODSID)
			  IF @BILLTYPE=2
			 BEGIN
			   SELECT @BILLCODE=(SELECT CODE   FROM STOREXSCKM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STOREXSCKM  WHERE BILLID=@BILLID)
			   SELECT @CLIENTID=(SELECT CLIENTID   FROM STOREXSCKM  WHERE BILLID=@BILLID)
			END
			  IF @BILLTYPE=12
			 BEGIN
			   SELECT @BILLCODE=(SELECT CODE   FROM STOREXSTHM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STOREXSTHM  WHERE BILLID=@BILLID)
			   SELECT @CLIENTID=(SELECT CLIENTID   FROM STOREXSTHM  WHERE BILLID=@BILLID)
			END
	                 SELECT  @CLIENTNAME =(SELECT NAME   FROM ViewCLIENT  WHERE CLIENTID=@CLIENTID  and CLIENTFlag=@CLIENTFlag)

				set   @PRICE=@AMT/@QUANTITY

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,CLIENTNAME,UNIT, QUANTITY,PRICE,APRICE,TAXRATE, AMT,XSCBAMT)
             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@CLIENTNAME,@UNIT,@QUANTITY,@PRICE,@APRICE,@TAXRATE,
					ROUND(@QUANTITY*@PRICE*@DISC*0.01,2),ROUND(@QUANTITY*@APRICE,2))
				SELECT @SUMAMT=@SUMAMT+ROUND(@QUANTITY*@PRICE*@DISC*0.01,2)
				SELECT @SUMXSCBAMT=@SUMXSCBAMT+ROUND(@QUANTITY*@APRICE,2)
		
	    fetch XSCKMLRMXB_XSCK into   @GOODSID,@BILLID,@PRICE,@APRICE,@DISC,@QUANTITY,@TAXRATE,@BILLTYPE,@AMT,@ClientFlag
 
	    END           ------- XSCKMLRMXB_XSCK  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,AMT,XSCBAMT)
                                           VALUES  (@COUNTID, '小计',@SUMAMT,@SUMXSCBAMT)

	    close XSCKMLRMXB_XSCK
	    deallocate XSCKMLRMXB_XSCK
        end     ------------  if exists

	UPDATE   #temptable2   SET MLRAMT=AMT- XSCBAMT
	UPDATE   #temptable2   SET MLV=(MLRAMT/ AMT)*100   WHERE AMT<>0

 SELECT *  FROM #temptable2         ORDER BY ID








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE GOODSXSCKMXB( @WHERESTING   varchar(1800)
                       
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8)

declare @CLIENTNAME  varchar(50)

declare @ID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @BILLTYPE  INT
declare @PRICETYPE  INT
declare @CLIENTID  nvarchar(50)
declare @GOODSNAME  nvarchar(50)
declare @GOODSCODE  nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLCODE  nvarchar(50)
declare @BILLDATE  datetime
declare @GOODSID00  nvarchar(50)
declare @PRICE NUMERIC(20,10)
declare @QUANTITY NUMERIC(20,10)
declare @TAXRATE  NUMERIC(20,10)
declare @FuZhuQTY  varchar(50)
declare @SUMAMT NUMERIC(20,10)
declare @DISC NUMERIC(20,10)
declare @SUMTAXAMT NUMERIC(20,10)
declare @AMT NUMERIC(20,10)
declare @TAXAMT NUMERIC(20,10)
declare @UNITPRICE  NUMERIC(20,10)
declare @UNITQTY  NUMERIC(20,10)
declare @ClientFlag smallint 
declare @DunQTY NUMERIC(20,10)
declare @Rate NUMERIC(20,10)
declare @SumDunQTY NUMERIC(20,10)
    

Create Table #temptable1
      (GOODSID  varchar(10) ,
             GOODSCODE nvarchar(50)  NULL,
             BILLID  nvarchar(50)  NULL,
             BILLTYPE INT,
	[PRICE] NUMERIC(20,10)  NULL ,
	[DISC] NUMERIC(20,10)  NULL ,
	[QUANTITY] NUMERIC(20,10)  NULL ,
	[TAXRATE]NUMERIC(20,10)  NULL ,
	FuZhuQTY  varchar(50)  NULL,
	BILLDATE DATEtime,
	[UNITPRICE] NUMERIC(20,10)  NULL ,
	[UNITQTY]NUMERIC(20,10)  NULL ,
		     PRICETYPE  INT ,
	[AMT]NUMERIC(20,10)  NULL ,
	[TAXAMT]NUMERIC(20,10)  NULL, 
	[ClientFlag]smallint  NULL 
	)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select    VIEWXSCK.GOODSID,GOODS.CODE AS GOODSCODE, BILLID,BILLTYPE,VIEWXSCK.PRICE,DISC,QUANTITY,TAXRATE,FuZhuQTY,BILLDATE  '
           SELECT  @SQLSTR = @SQLSTR+' ,UNITPRICE,UNITQTY,PRICETYPE,AMT,TAXAMT,ClientFlag from VIEWXSCK   ,GOODS  '  + @WHERESTING +'  AND  VIEWXSCK.GOODSID = GOODS.GOODSID'
           SELECT  @SQLSTR = @SQLSTR+'  order by VIEWXSCK.GOODSID,BILLDATE,BILLID '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   CLIENTNAME  nvarchar(50)  NULL,
   UNIT  nvarchar(10)  NULL,
	[QUANTITY] NUMERIC(20,10)  NULL ,
	[PRICE] NUMERIC(20,10)  NULL ,
	[TAXRATE]NUMERIC(20,10)  NULL ,
	FuZhuQTY  varchar(50)  NULL,
	[AMT]NUMERIC(20,10)  NULL ,
	[TAXAMT]NUMERIC(20,10)  NULL ,
   		PRICETYPENAME  nvarchar(10)  NULL,
	[DunQTY]NUMERIC(20,10)  NULL 
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (select   GOODSID, BILLID,PRICE,DISC,QUANTITY,TAXRATE   from  #temptable1        )
                 begin
	    declare XSCKMXB_XSCK Cursor for select   GOODSID, BILLID,PRICE,DISC,QUANTITY,TAXRATE,FuZhuQTY,BILLTYPE,UNITPRICE,UNITQTY,PRICETYPE,AMT,TAXAMT,ClientFlag  from  #temptable1  
                                                            ORDER BY  GOODSCODE,BILLDATE, BILLID
	    Open XSCKMXB_XSCK

	    fetch XSCKMXB_XSCK into   @GOODSID,@BILLID,@PRICE,@DISC,@QUANTITY,@TAXRATE,@FuZhuQTY,@BILLTYPE,@UNITPRICE,@UNITQTY,@PRICETYPE,@AMT,@TAXAMT,@ClientFlag

                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @GOODSCODE='商品编码：'+@GOODSCODE
                 SELECT  @GOODSID00=@GOODSID

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,CLIENTNAME         )
                                           VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
		SELECT @SUMAMT=0
		SELECT @SUMTAXAMT=0
		SELECT @SUMDunQTY=0
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF  not( @GOODSID00 = @GOODSID)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,AMT,TAXAMT,DunQTY)
                                           VALUES  (@COUNTID, '小计',@SUMAMT,@SUMTAXAMT,@SumDunQTY)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @GOODSCODE='商品编码：'+@GOODSCODE
		                 SELECT  @GOODSID00=@GOODSID

			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                          INSERT    INTO   #temptable2  (ID, BILLCODE,CLIENTNAME    )
                           	                VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
				SELECT @SUMAMT=0
				SELECT @SUMTAXAMT=0
				SELECT @SUMDunQTY=0
		END	
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
	  			SELECT @UNIT = (SELECT UNIT   FROM GOODS  WHERE GOODSID=@GOODSID)
			  IF @BILLTYPE=2
			 BEGIN
			   SELECT @BILLCODE=(SELECT CODE   FROM STOREXSCKM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STOREXSCKM  WHERE BILLID=@BILLID)
			   SELECT @CLIENTID=(SELECT CLIENTID   FROM STOREXSCKM  WHERE BILLID=@BILLID)
			END
			  IF @BILLTYPE=12
			 BEGIN
			   SELECT @BILLCODE=(SELECT CODE   FROM STOREXSTHM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STOREXSTHM  WHERE BILLID=@BILLID)
			   SELECT @CLIENTID=(SELECT CLIENTID   FROM STOREXSTHM  WHERE BILLID=@BILLID)
			END
	                 SELECT  @CLIENTNAME =(SELECT NAME   FROM ViewCLIENT  WHERE CLIENTID=@CLIENTID  and CLIENTFlag=@CLIENTFlag)

				IF @PRICETYPE=1 
				BEGIN
			                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,CLIENTNAME,UNIT, QUANTITY,PRICE,TAXRATE,FuZhuQTY, AMT,TAXAMT,PRICETYPENAME,DunQTY)
	             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@CLIENTNAME,@UNIT,@UNITQTY,@unitPRICE,@TAXRATE,@FuZhuQTY,@AMT,@TAXAMT,'重量',@QUANTITY)
					set @DunQTY=@QUANTITY
				END
				IF @PRICETYPE=0
				BEGIN
		                 SELECT  @Rate =(SELECT ISNULL(Rate,0)*0.001 FROM GOODS  WHERE GOODSID=@GOODSID)
			                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,CLIENTNAME,UNIT, QUANTITY,PRICE,TAXRATE,FuZhuQTY, AMT,TAXAMT,PRICETYPENAME,DunQTY)
	             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@CLIENTNAME,@UNIT,@UNITQTY,@UNITPRICE,@TAXRATE,@FuZhuQTY,@AMT,@TAXAMT,'数量',@Rate*@UNITQTY)
					set @DunQTY=@Rate*@UNITQTY
				END
				SELECT @SUMAMT=@SUMAMT+@AMT
				SELECT @SUMTAXAMT=@SUMTAXAMT+@TAXAMT
				SELECT @SUMDunQTY=@SUMDunQTY+@DunQTY
		
	    fetch XSCKMXB_XSCK into   @GOODSID,@BILLID,@PRICE,@DISC,@QUANTITY,@TAXRATE,@FuZhuQTY,@BILLTYPE,@UNITPRICE,@UNITQTY,@PRICETYPE,@AMT,@TAXAMT,@ClientFlag
 
	    END           ------- XSCKMXB_XSCK  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,AMT,TAXAMT,DunQTY)
                                           VALUES  (@COUNTID, '小计',@SUMAMT,@SUMTAXAMT,@SumDunQTY)

	    close XSCKMXB_XSCK
	    deallocate XSCKMXB_XSCK
        end     ------------  if exists

 SELECT *  FROM #temptable2         ORDER BY ID









----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG








--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE [dbo].[GOODSXSDDMXB]( @WHERESTING   varchar(1800)
                       
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8)

declare @CLIENTNAME  varchar(50)
declare @GOODSNAME  varchar(50)

declare @ID  nvarchar(50)
declare @CLIENTID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @CLIENTCODE  nvarchar(50)
declare @GOODSCODE  nvarchar(50)
declare @SPECNAME nvarchar(50)
declare @MODELNAME nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLCODE  nvarchar(50)
declare @BILLTYPE INT
declare @BILLDATE  datetime
declare @GOODSID00  nvarchar(50)
declare @PRICE NUMERIC(20, 6)
declare @TAXAMT NUMERIC(20, 2)
declare @WCunitQTY NUMERIC(20, 6)
declare @WCquantity NUMERIC(20, 6)
declare @zzunitQTY NUMERIC(20, 6)
declare @zzquantity NUMERIC(20, 6)
declare @WCTAXAMT NUMERIC(20, 6)
declare @TAXRATE  NUMERIC(20, 6)
declare @RATE  NUMERIC(20, 6)
declare @WEITAXAMT NUMERIC(20, 6)
declare @SUMWCTAXAMT NUMERIC(20, 6)
declare @SUMWEITAXAMT NUMERIC(20, 6)
declare @SUMTAXAMT NUMERIC(20, 6)
declare @UNITQTY NUMERIC(20, 6)
declare @quantity NUMERIC(20, 6)
declare @UNITPRICE NUMERIC(20, 6)
declare @DISC NUMERIC(20, 6)
declare    @PRICETYPE int

Create Table #temptable1
      (   GOODSID varchar(50)  NULL,
       CLIENTID  varchar(10) ,
       CLIENTCODE  varchar(30) ,
      BILLID  nvarchar(50)  NULL,
      BILLTYPE  INT ,
	[PRICE] NUMERIC(20, 6)  NULL ,
	[UNITQTY] NUMERIC(20, 6)  NULL ,
	[quantity] NUMERIC(20, 6)  NULL ,
	[DISC] NUMERIC(20, 6)  NULL ,
	[TAXRATE]NUMERIC(20, 6)  NULL ,
	   BILLDATE  datetime  NULL,
	[UNITPRICE] NUMERIC(20, 6)  NULL ,
	[WCunitQTY]NUMERIC(20, 6)  NULL ,
	[WCquantity]NUMERIC(20, 6)  NULL ,
	[zzunitQTY]NUMERIC(20, 6)  NULL ,
	[zzquantity]NUMERIC(20, 6)  NULL ,
	[TAXAMT]NUMERIC(20, 2)  NULL, 
	[PRICETYPE]    int  NULL, 
	       DETAILBILLFLOWID  varchar(10) 
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   VIEWXSDD.GOODSID,VIEWXSDD.CLIENTID,CLIENT.CODE AS CLIENTCODE, BILLID,BILLTYPE,PRICE,UNITQTY,quantity,DISC,TAXRATE,BILLDATE '
           SELECT  @SQLSTR = @SQLSTR+' ,UNITPRICE,WCunitQTY,WCquantity,zzunitQTY,zzquantity,TAXAMT,PRICETYPE,DETAILBILLFLOWID  from VIEWXSDD   ,CLIENT  '  + @WHERESTING +'  AND  VIEWXSDD.CLIENTID = CLIENT.CLIENTID'
           SELECT  @SQLSTR = @SQLSTR+'  order by VIEWXSDD.GOODSID,VIEWXSDD.CLIENTID,BILLDATE,DETAILBILLFLOWID '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
	   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   CLIENTNAME  nvarchar(50)  NULL,
   CLIENTCODE  nvarchar(50)  NULL,
   UNIT  nvarchar(10)  NULL,
	[UNITQTY] NUMERIC(20, 6)  NULL ,
	[quantity] NUMERIC(20, 6)  NULL ,
	[TAXAMT]NUMERIC(20, 2)  NULL, 
	[WCunitQTY] NUMERIC(20, 6)  NULL ,
	[WCquantity] NUMERIC(20, 6)  NULL ,
	[zzunitQTY] NUMERIC(20, 6)  NULL ,
	[zzquantity] NUMERIC(20, 6)  NULL ,
	[WCTAXAMT]NUMERIC(20, 6)  NULL ,
	[WEIunitQTY] NUMERIC(20, 6)  NULL ,
	[WEIquantity] NUMERIC(20, 6)  NULL ,
	[WEITAXAMT]NUMERIC(20, 6)  NULL 
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (select  GOODSID, CLIENTID, BILLID,PRICE,UNITQTY,TAXRATE,BILLTYPE   from  #temptable1        )
                 begin
	    declare XSDDMXB_GOODS Cursor for select  GOODSID, CLIENTID, BILLID,PRICE,UNITQTY,quantity,TAXRATE,BILLTYPE ,DISC,UNITPRICE,WCunitQTY,WCquantity, zzunitQTY,zzquantity,TAXAMT,PRICETYPE  from  #temptable1  
---                                                            ORDER BY  GOODSID,  BILLDATE,DETAILBILLFLOWID,CLIENTCODE
                                                            ORDER BY  GOODSID,  BILLDATE,BILLID,CLIENTCODE
	    Open XSDDMXB_GOODS

	    fetch XSDDMXB_GOODS into   @GOODSID,@CLIENTID,@BILLID,@PRICE,@UNITQTY,@quantity,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@WCunitQTY,@WCquantity,@zzunitQTY,@zzquantity,@TAXAMT,@PRICETYPE

                 SELECT  @CLIENTNAME =(SELECT NAME   FROM CLIENT  WHERE CLIENTID=@CLIENTID)
                 SELECT  @CLIENTCODE =(SELECT CODE  FROM CLIENT  WHERE CLIENTID=@CLIENTID)
                 SELECT  @GOODSCODE=CODE,@GOODSNAME=Name,@SpecName=SpecName,@ModelName=ModelName     FROM GOODS  WHERE GOODSID=@GOODSID
                 SELECT  @GOODSNAME =@GOODSNAME+' '+ISNULL(@SpecName,'')+' '+ISNULL(@ModelName,'')
                 SELECT  @GOODSCODE='钢材编码：'+@GOODSCODE

                 SELECT  @GOODSID00=@GOODSID

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,CLIENTNAME         )
                                           VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
		SELECT @SUMWCTAXAMT=0
		SELECT @SUMTAXAMT=0
		SELECT @SUMWEITAXAMT=0
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF  not( @GOODSID00 = @GOODSID)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,WCTAXAMT,TAXAMT,WEITAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMWCTAXAMT,@SUMTAXAMT,@SUMWEITAXAMT)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

		                 SELECT  @CLIENTNAME =(SELECT NAME   FROM CLIENT  WHERE CLIENTID=@CLIENTID)
		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @CLIENTCODE =(SELECT CODE  FROM CLIENT  WHERE CLIENTID=@CLIENTID)
                 SELECT  @GOODSCODE=CODE,@GOODSNAME=Name,@SpecName=SpecName,@ModelName=ModelName     FROM GOODS  WHERE GOODSID=@GOODSID
                 SELECT  @GOODSNAME =@GOODSNAME+' '+ISNULL(@SpecName,'')+' '+ISNULL(@ModelName,'')
                 SELECT  @GOODSCODE='钢材编码：'+@GOODSCODE
		                 
		                 SELECT  @GOODSID00=@GOODSID


			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,CLIENTNAME         )
                                           VALUES  (@COUNTID,@GOODSNAME, @GOODSCODE)
				SELECT @SUMWCTAXAMT=0
				SELECT @SUMTAXAMT=0
				SELECT @SUMWEITAXAMT=0
		END	
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

				--SELECT @RATE =RATE  FROM CLIENTUNIT  WHERE CLIENTID=@CLIENTID AND UNITID=@UNITID

			SELECT @UNIT = UNIT   FROM GOODS  WHERE GOODSID=@GOODSID
				
			   SELECT @BILLCODE=(SELECT CODE   FROM STOREXSDDM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STOREXSDDM  WHERE BILLID=@BILLID)
		                 SELECT  @CLIENTNAME=(SELECT NAME   FROM CLIENT  WHERE CLIENTID=@CLIENTID)
		                 SELECT  @CLIENTCODE=(SELECT CODE   FROM CLIENT  WHERE CLIENTID=@CLIENTID)
		               if @PRICETYPE=1
		               begin  
		                 SET @WEITAXAMT=Round(ISNULL(@DISC,100)*0.01*(ISNULL(@quantity,0)-ISNULL(@WCquantity,0)-ISNULL(@zzquantity,0))*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
		                 SET @WCTAXAMT=Round(ISNULL(@DISC,100)*0.01*ISNULL(@WCquantity,0)*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
					   end
					   else
					   begin
		                 SET @WEITAXAMT=Round(ISNULL(@DISC,100)*0.01*(ISNULL(@unitqty,0)-ISNULL(@WCunitqty,0)-ISNULL(@zzunitqty,0))*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
		                 SET @WCTAXAMT=Round(ISNULL(@DISC,100)*0.01*ISNULL(@WCunitqty,0)*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
					   end
		                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,CLIENTNAME,CLIENTCODE,UNIT, UNITQTY,quantity,TAXAMT,WCunitQTY,WCquantity,zzunitQTY,zzquantity,WCTAXAMT,WEIunitQTY,WEIquantity,WEITAXAMT)
             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@CLIENTNAME,@CLIENTCODE,@UNIT,@UNITQTY,@quantity,
					                     @TAXAMT,
					                     ISNULL(@WCunitQTY,0) ,
					                     ISNULL(@WCquantity,0) ,
					                     ISNULL(@zzunitQTY,0) ,
					                     ISNULL(@zzquantity,0) ,					@WCTAXAMT,
					                      @UNITQTY-ISNULL(@WCunitQTY,0) -ISNULL(@zzunitQTY,0),
					                      @quantity-ISNULL(@WCquantity,0) -ISNULL(@zzquantity,0),@WEITAXAMT	)

				SELECT @SUMTAXAMT=@SUMTAXAMT+@TAXAMT
				SELECT @SUMWCTAXAMT=@SUMWCTAXAMT+@WCTAXAMT
				SELECT @SUMWEITAXAMT=@SUMWEITAXAMT+@WEITAXAMT
		
	    fetch XSDDMXB_GOODS into   @GOODSID,@CLIENTID,@BILLID,@PRICE,@UNITQTY,@quantity,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@WCunitQTY,@WCquantity,@zzunitQTY,@zzquantity,@TAXAMT,@PRICETYPE
 
	    END           ------- XSDDMXB_GOODS  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,WCTAXAMT,TAXAMT,WEITAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMWCTAXAMT,@SUMTAXAMT,@SUMWEITAXAMT)

	    close XSDDMXB_GOODS
	    deallocate XSDDMXB_GOODS
        end     ------------  if exists

 SELECT *  FROM #temptable2         ORDER BY ID













----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG




















--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE GOODS_STOREMXB( @WHERESTING   varchar(1800),
                                  @ShowFLAG   smallint,      --------同价调拨标志   0  代表 不作为过滤条件
                                  @LiuHuoShowFLAG   smallint      --------同价调拨标志   0  代表 不作为过滤条件

                      
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @SQLSTR00   varchar(800),
        @SQLSTR2005   varchar(800),
        @COUNTID   varchar(8)

declare @CLIENTNAME  varchar(50)

declare @ID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @STOREID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @CLIENTID  nvarchar(50)
declare @GOODSNAME  nvarchar(50)
declare @GOODSCODE  nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLCODE  nvarchar(50)
declare @YYYYMM  nvarchar(50)
declare @STORENAME  nvarchar(50)
declare @BILLDATE  datetime
declare @GOODSID00  nvarchar(50)
declare @PRICE NUMERIC(16,4)
declare @QUANTITY NUMERIC(16,4)
declare @STOREIDEQTY NUMERIC(16,4)
declare @TAXRATE  NUMERIC(16,4)
declare @SUMQTY NUMERIC(16,4)
declare @APRICE NUMERIC(16,4)
declare @DISC NUMERIC(16,4)
declare @SUMXSCBAMT NUMERIC(16,4)
declare @NameLen int
declare @SpecNameLen int


 		SELECT @YYYYMM=( SELECT   optionvalue     FROM  accoptionS     where optionname ='YYYYMM')






/*Create Table DB_STORELEDGER
      (GOODSID  varchar(10) ,
       StoreID  varchar(10) ,
	  EQTY NUMERIC(16,4)  NULL, 
	  MEQTY NUMERIC(16,4)  NULL 
		)
*/
----------------------------------------------------
/*Create Table DB_STORELEDGER_Root
      (StoreID  varchar(10) ,
       GOODSID  varchar(10) 
		)
*/
----------------------------------------------------
			delete DB_STORELEDGER_Root

			INSERT INTO  DB_STORELEDGER_Root select distinct StoreID,GOODSID from DETAILBILLFLOW

			delete DB_STORELEDGER

		SELECT @SQLSTR='	 select  I.GOODSID,I.StoreID,       '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)+ isnull(E.INQTY,0)  as EQTY, '   --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0)  as MEQTY '   --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from DB_STORELEDGER_Root  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,StoreID,sum(INQTY*INOUTFLAG)  as INQTY  ,sum(MINQTY*INOUTFLAG)  as MINQTY '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID,StoreID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID AND  E.StoreID = I.StoreID '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,StoreID,sum(BQTY) as BQTY ,sum(MBQTY) as MBQTY '
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID,StoreID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID AND B.StoreID = I.StoreID '
------------------------以上部分是取当前库存
----		print @SQLSTR

		INSERT INTO  DB_STORELEDGER  EXEC(@SQLSTR)


-----------------------------------------------------------------------------------------


	if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[GOODSSTORETMP]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
	drop table [dbo].[GOODSSTORETMP]


----
		select @NameLen=max(Len(Name)) from Goods
		select @NameLen=2*(@NameLen+1) 
		select @SpecNameLen=max(Len(SpecName)) from Goods
		select @SpecNameLen=1.5*(@SpecNameLen+1) 


	    if @LiuHuoShowFLAG =1 
	    begin
	    declare STORE_XSCK Cursor for select   STOREID   from  STORE    ORDER BY CODE
 	    end
	    else
	    begin
	    declare STORE_XSCK Cursor for select   STOREID   from  STORE  where liuhflag<>1   ORDER BY CODE
 	    end

	  
	    Open   STORE_XSCK

	    fetch    STORE_XSCK into   @STOREID
	           SELECT  @SQLSTR = 'Create Table GOODSSTORETMP (  '
	           SELECT  @SQLSTR = @SQLSTR+' 商品编码 [varchar] (20), '
---	           SELECT  @SQLSTR = @SQLSTR+' 商品名称 [varchar] (80), '
	           SELECT  @SQLSTR = @SQLSTR+' 商品名称 [varchar] ('+convert(char,@NameLen)+'), '
---	           SELECT  @SQLSTR = @SQLSTR+' 规格   [varchar] (50), '
	           SELECT  @SQLSTR = @SQLSTR+' 规格   [varchar] ('+convert(char,@SpecNameLen)+'), '
	           SELECT  @SQLSTR = @SQLSTR+' 单位   [varchar] (8), '

	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    BEGIN

	           SELECT  @SQLSTR =@SQLSTR+'['+@STOREID+']'+' NUMERIC(16,4)  NULL ,'

		    fetch    STORE_XSCK into   @STOREID

	    END
	    close  STORE_XSCK
	    deallocate  STORE_XSCK

	           SELECT  @SQLSTR =@SQLSTR+'   合计   NUMERIC(16,4)  NULL )  '

                EXEC( @SQLSTR)

		set  @SQLSTR2005 =' 	insert  into   GOODSSTORETMP (商品编码,商品名称,规格,单位)    '
		set  @SQLSTR2005 =@SQLSTR2005+'	  SELECT  CODE,NAME,SPECNAME,UNIT  FROM GOODS  '
		set  @SQLSTR2005 =@SQLSTR2005+'	  WHERE GOODSID IN (SELECT GOODSID FROM DETAILBILLFLOW)  '+@WHERESTING
		exec(@SQLSTR2005)

--				insert  into   GOODSSTORETMP (商品编码,商品名称,规格,单位)    
--				  SELECT  CODE,NAME,SPECNAME,UNIT  FROM GOODS  
--				  WHERE GOODSID IN (SELECT GOODSID FROM DETAILBILLFLOW) 

-------------------------------以上是创建数据库


	    declare STORE_TMP Cursor for select   商品编码   from  GOODSSTORETMP

                                                                 ORDER BY 商品编码
	    Open   STORE_TMP

	    fetch    STORE_TMP into   @GOODSCODE


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    BEGIN
		SET @SUMQTY=0

		SELECT @GOODSID=(SELECT GOODSID FROM GOODS WHERE CODE= @GOODSCODE)
	    if @LiuHuoShowFLAG =1 
	    begin

		    declare STORE_XSCK00 Cursor for select   STOREID   from  STORE  ORDER BY CODE
 	    end
	    else
	    begin
		    declare STORE_XSCK00 Cursor for select   STOREID   from  STORE  where liuhflag<>1   ORDER BY CODE
 	    end


		    Open   STORE_XSCK00

		    fetch    STORE_XSCK00 into   @STOREID

		    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
		    BEGIN

				SET @STOREIDEQTY=0
				IF @ShowFLAG =1
				begin
---        	                    	 EXEC   GETGOODSIDMEQTY  @STOREID,@GOODSID,@YYYYMM,@MEQTY=@STOREIDEQTY   OUTPUT
					select @STOREIDEQTY=MEQTY from DB_STORELEDGER where GoodsID=@GOODSID and STOREID=@STOREID
				end
				IF @ShowFLAG =2
				begin
---	                              EXEC   GETGOODSIDEQTY     @STOREID,@GOODSID,@YYYYMM,@EQTY=@STOREIDEQTY   OUTPUT
					select @STOREIDEQTY=EQTY from DB_STORELEDGER where GoodsID=@GOODSID and STOREID=@STOREID
				end
				
				SET @SUMQTY=@SUMQTY+ISNULL(@STOREIDEQTY,0)
	
				SET @SQLSTR00 ='     UPDATE   GOODSSTORETMP  set  '+'['+@STOREID+']'+' ='+ CAST(@STOREIDEQTY  AS varchar(30))  +'   WHERE  商品编码='+CHAR(39)+@GOODSCODE+CHAR(39) 
				                EXEC( @SQLSTR00)

			    fetch    STORE_XSCK00  into   @STOREID

		    END
		    close  STORE_XSCK00
		    deallocate  STORE_XSCK00

			UPDATE GOODSSTORETMP  SET  合计=@SUMQTY   WHERE  商品编码=@GOODSCODE
		    fetch    STORE_TMP into   @GOODSCODE

	    END
	    close  STORE_TMP
	    deallocate  STORE_TMP

-------------------------
	    if @LiuHuoShowFLAG =1 
	    begin
	    declare STORE_XSCK Cursor for select   STOREID,STORENAME   from  STORE  ORDER BY CODE
 	    end
	    else
	    begin
	    declare STORE_XSCK Cursor for select   STOREID,STORENAME   from  STORE  where liuhflag<>1   ORDER BY CODE
 	    end

	    Open   STORE_XSCK

	    fetch    STORE_XSCK into   @STOREID,@STORENAME

	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    BEGIN


	           SELECT  @SQLSTR ='ALTER TABLE  GOODSSTORETMP  ADD  '+'['+@STORENAME+']'+' NUMERIC(16,4)  NULL '
		                EXEC( @SQLSTR)
	           SELECT  @SQLSTR ='UPDATE  GOODSSTORETMP   SET   '+'['+@STORENAME+']'+' = ['+@STOREID+']'
		                EXEC( @SQLSTR)
	           SELECT  @SQLSTR ='ALTER TABLE  GOODSSTORETMP  DROP   COLUMN '+'['+@STOREID+']'
		                EXEC( @SQLSTR)
		    fetch    STORE_XSCK into   @STOREID,@STORENAME

	    END
	    close  STORE_XSCK
	    deallocate  STORE_XSCK


  SELECT   *    FROM  GOODSSTORETMP  where 合计 <>0  ORDER BY 商品编码  











----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












-------本会计期间返回值为 Billdate >=@MINBILLDATE  AND  Billdate<@MAXBILLDATE

--------------------------------------------------------------------

CREATE PROCEDURE Get_Max_Min_Date  
                 (
                  @MAXBILLDATE DATEtime output,     ---返回记帐成功  -- 0 不在此会计期间  --1 在会计期间
                  @MINBILLDATE DATEtime output     ---返回记帐成功  -- 0 不在此会计期间  --1 在会计期间
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     

---declare @MINBILLDATE DATEtime
---declare @MAXBILLDATE DATEtime


   declare  @PREV_YYYYMM          varchar(6)  -- 上一个会计年月
   declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='CW_YYYYMM')  

   
	if substring(@YYYYMM,5,2) = '12'  --- 如果当前会计月等于最大的会计月，将需要转入下年的的第一个会计年月
	begin
	    set @Next_YYYYMM   = convert(varchar,convert(int,substring(@YYYYMM,1,4))+1) +'01'  
	end
	else
	begin
	    set @Next_YYYYMM   = substring(@YYYYMM,1,4) +substring('00',1,2-len(convert(varchar,convert(int,substring(@YYYYMM,5,2))+1)))+convert(varchar,convert(int,substring(@YYYYMM,5,2))+1)
	end

	if substring(@YYYYMM,5,2) = '01'  --- 如果当前会计月等于最大的会计月，将需要转入下年的的第一个会计年月
	begin
	    set @PREV_YYYYMM   = convert(varchar,convert(int,substring(@YYYYMM,1,4))-1) +'12'  
	end
	else
	begin
	    set @PREV_YYYYMM   = substring(@YYYYMM,1,4) +substring('00',1,2-len(convert(varchar,convert(int,substring(@YYYYMM,5,2))-1)))+convert(varchar,convert(int,substring(@YYYYMM,5,2))-1)
	end

	declare @YYYYMMFS INTEGER
	declare @YYYYMMFSDATE  INTEGER
	declare @Billday  INTEGER

	       SELECT    @YYYYMMFS =(SELECT  YYYYMMFS   FROM   ACCINFO    WHERE   GUID='0001' )    
                IF @YYYYMMFS=1
	  BEGIN
		     SET  @MINBillDate = CONVERT(DATEtime,@YYYYMM+'01')
		     SET  @MAXBillDate =CONVERT(DATEtime,@Next_YYYYMM+'01')
	  END
               ELSE
               BEGIN
	       SELECT    @YYYYMMFSDATE =(SELECT  YYYYMMFSDATE   FROM   ACCINFO    WHERE   GUID='0001' )    
       
	     SET  @MINBillDate =DATEADD(day, @YYYYMMFSDATE, CONVERT(DATEtime,@PREV_YYYYMM+'01'))
	     SET  @MAXBillDate =DATEADD(day, @YYYYMMFSDATE, CONVERT(DATEtime,@YYYYMM+'01'))
	 END



----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












--------------------------------------------------------------------
--------------------------------------------------------------------

CREATE PROCEDURE INSERTTOSecurity (
                              @USERID   varchar(20),   --传入当前操作员
                              @IsSuccess         int output     ---返回成功  -- 0 不成功  --1 
                            )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
Begin transaction SMDataToNext

                      UPDATE FunctionM  SET USERID=@USERID
                      INSERT INTO Security  (USERID,Function_id ,Parent_Function_Id,Control_Type )
                                 SELECT    USERID, Function_id ,Parent_Function_Id,Control_Type      FROM  FunctionM  where Function_id  not in (select Function_id   from  Security  where  USERID=@USERID)  
                      update  Security   set    CANACCESS=1      where  userid='0001'
                      DELETE   FROM    Security    WHERE   Function_id NOT  IN ( SELECT  Function_id   FROM     FunctionM         )


--写结转信息
  If @@error = 0
  begin
     commit transaction SMDataToNext
   set @IsSuccess=1
  end
  else
  begin
    rollback transaction SMDataToNext
   set @IsSuccess=0
    raiserror('结转失败 ', 1, 20) 
  end
  







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














----------------------------------------------------------------------------
CREATE PROCEDURE [QTSRBILLTREE]  (  @INSQLSTRING  varchar(300)    )  --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
 

Declare @SQL				varchar(8000)

 
BEGIN

	SELECT @SQL= 'select SUBSTRING(GOODSNOJS,1,4) as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWQTSRJSNO'
	SELECT @SQL=@SQL+'  WHERE   SUBSTRING(GOODSNOJS,1,4) in (select lcode FROM INTYPE)    ' +@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY SUBSTRING(GOODSNOJS,1,4)'
	SELECT @SQL=@SQL+' union '
	SELECT @SQL=@SQL+' select SUBSTRING(GOODSNOJS,5,4) as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWQTSRJSNO'
	SELECT @SQL=@SQL+'  where   SUBSTRING(GOODSNOJS,5,4) in (select lcode FROM INTYPE) '+@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY SUBSTRING(GOODSNOJS,5,4)'
	SELECT @SQL=@SQL+' union '
	SELECT @SQL=@SQL+' select SUBSTRING(GOODSNOJS,9,4) as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWQTSRJSNO'
	SELECT @SQL=@SQL+'  where   SUBSTRING(GOODSNOJS,9,4) in (select lcode FROM INTYPE) '+@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY SUBSTRING(GOODSNOJS,9,4)'
	SELECT @SQL=@SQL+' union '
	SELECT @SQL=@SQL+' select SUBSTRING(GOODSNOJS,13,4) as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWQTSRJSNO'
	SELECT @SQL=@SQL+'  where   SUBSTRING(GOODSNOJS,13,4) in (select lcode FROM INTYPE) '+@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY SUBSTRING(GOODSNOJS,13,4)'
	SELECT @SQL=@SQL+' union '
	SELECT @SQL=@SQL+' select SUBSTRING(GOODSNOJS,17,4) as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWQTSRJSNO'
	SELECT @SQL=@SQL+'  where   SUBSTRING(GOODSNOJS,17,4) in (select lcode FROM INTYPE) '+@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY SUBSTRING(GOODSNOJS,17,4)'
	SELECT @SQL=@SQL+' union '
	SELECT @SQL=@SQL+' select SUBSTRING(GOODSNOJS,21,4) as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWQTSRJSNO'
	SELECT @SQL=@SQL+'  where   SUBSTRING(GOODSNOJS,21,4) in (select lcode FROM INTYPE) '+@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY SUBSTRING(GOODSNOJS,21,4)'
	SELECT @SQL=@SQL+' union '
	SELECT @SQL=@SQL+' select  STOREID as LCODE ,sum(QUANTITY) as QUANTITY    from VIEWQTSRJSNO'
	SELECT @SQL=@SQL+'  where   1 = 1 '+@INSQLSTRING
	SELECT @SQL=@SQL+'  GROUP BY STOREID '
		EXEC(@SQL)
----注意INTYPE  中的LCODE不能和GOODS中的STOREID 重码，以后补充检测过程
------------------------------------------------------------------------------------


END







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG










--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[SM_DataToNext] (
                              @Current_YYYYMM   varchar(20),   --传入当前会计期间
                              @IsSuccess         int output     ---返回成功  -- 0 不成功  --1 
                            )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
Begin transaction SMDataToNext
   declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月
   declare  @SQLSTR         varchar(8000)  -- 下一个会计年月


declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。


declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)

declare @YYYYMMBILL int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @CLIENTID varchar(15)               --明细存货
declare @VENDORID varchar(15)               --明细存货编号
declare @YunShuDWID varchar(15)               --明细存货编号
declare @BANKID varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @Bqty NUMERIC(20,10)                          --数量
declare @BAMOUNT NUMERIC(20,10)                          --数量
declare @MBQTY NUMERIC(20,10)                          --数量
declare @MEQTY NUMERIC(20,10)                          --数量
declare @Eqty NUMERIC(20,10)                          --数量
declare @EAMOUNT NUMERIC(20,10)                          --数量
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @B_ID INTEGER


if substring(@Current_YYYYMM,5,2) = '12'  --- 如果当前会计月等于最大的会计月，将需要转入下年的的第一个会计年月
begin
    set @Next_YYYYMM   = convert(varchar,convert(int,substring(@Current_YYYYMM,1,4))+1) +'01'  
end
else
begin
    set @Next_YYYYMM   = substring(@Current_YYYYMM,1,4) +substring('00',1,2-len(convert(varchar,convert(int,substring(@Current_YYYYMM,5,2))+1)))+convert(varchar,convert(int,substring(@Current_YYYYMM,5,2))+1)
end


--判断当前会计期间是否月结，不能重复月结

declare @flagreturn int 
exec STORE_YYYYMM_INSERT   @flagreturn output 


--------取得接转当前会计期间的数据并复制到临时表中 begin --------------------------------
delete  DETAILBILLFLOWTMP

----------------------------------------------------
		SELECT @SQLSTR='	 select DISTINCT I.YYYYMM,I.GOODSID,    I.STOREID,  INF_COSTINGTYPEID,YYYYMMBILL,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0) as BQTY, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0) as MBQTY, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0) as BAMOUNT, ' --期初金额
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)+ isnull(E.INQTY,0) '
		SELECT @SQLSTR=@SQLSTR+'  as EQTY ,' --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0) '
		SELECT @SQLSTR=@SQLSTR+'  as MEQTY ,' --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0)  '
                           SELECT @SQLSTR=@SQLSTR+'  as EAMOUNT    '--期初金额
		 SELECT @SQLSTR=@SQLSTR+'   from DETAILBILLFLOW  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,STOREID,sum(INQTY*INOUTFLAG)  as INQTY ,sum(MINQTY*INOUTFLAG)  as MINQTY ,sum(INQTY*INOUTFLAG*INPRICE)  as INAMOUNT '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM = '+char(39)+@Current_YYYYMM+char(39)                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID,STOREID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID    AND E.STOREID = I.STOREID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,STOREID,sum(BQTY) as BQTY ,sum(MBQTY) as MBQTY,SUM(BAMOUNT)  AS BAMOUNT '
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM ='+char(39)+@Current_YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID,STOREID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID    AND B.STOREID = I.STOREID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where   YYYYMM='+char(39)+@Current_YYYYMM+char(39)  +'  AND   YYYYMMBILL = 0'
		SELECT @SQLSTR=@SQLSTR+'          order by  I.GOODSID,I.STOREID           '
------------------------------------------------------------------------

		PRINT @SQLSTR
                       INSERT  INTO   DETAILBILLFLOWTMP (YYYYMM,GOODSID,STOREID,INF_COSTINGTYPEID,YYYYMMBILL,BQTY,MBQTY,BAMOUNT,EQTY,MEQTY,EAMOUNT)   EXEC(@SQLSTR)

update   DETAILBILLFLOWTMP  set YYYYMM=@Next_YYYYMM
update   DETAILBILLFLOWTMP  set BQTY=EQTY
update   DETAILBILLFLOWTMP  set MBQTY=MEQTY
update   DETAILBILLFLOWTMP  set BAMOUNT=EAMOUNT
           ---定义游标解决插入的ID问题

    declare SM_Consign_DATANEXT Cursor READ_ONLY for Select   YYYYMM,GOODSID,STOREID,INF_COSTINGTYPEID,YYYYMMBILL,BQTY,BAMOUNT,EQTY,EAMOUNT,MBQTY,MEQTY   from DETAILBILLFLOWTMP 

    Open SM_Consign_DATANEXT

    fetch SM_Consign_DATANEXT into @YYYYMM,@GOODSID,@STOREID,@INF_COSTINGTYPEID,@YYYYMMBILL,@BQTY,@BAMOUNT,@EQTY,@EAMOUNT,@MBQTY,@MEQTY

    while @@fetch_status = 0            ----开始
    begin
             		    execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
		    insert into DetailBillFlow 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLCODE,ITEMNO,GOODSID,
		     BQTY,BPRICE,BAMOUNT,INQTY,INPRICE,OUTQTY,OUTPRICE,MBQTY,MEQTY,
		     EQTY,EPRICE,EAMOUNT,STOREID,CACULATEFLAG,INOUTFLAG,DIFAMOUNT,INF_COSTINGTYPEID,
		     BATCHREFID,REFQTY,REFCOUNT )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillCode,@itemNo,@GoodsID,
		     @BQTY,0,@BAMOUNT,0,0,Null,Null,@MBQTY,@MEQTY,
		     @EQTY,@price,@EAMOUNT,@StoreID,'F',@inoutFlag,null,@INF_COSTINGTYPEID,
		     @B_ID,0,0   )    
    fetch SM_Consign_DATANEXT into @YYYYMM,@GOODSID,@STOREID,@INF_COSTINGTYPEID,@YYYYMMBILL,@BQTY,@BAMOUNT,@EQTY,@EAMOUNT,@MBQTY,@MEQTY

    END           ------- SM_Consign_DATANEXT  WHILE

    close SM_Consign_DATANEXT
    deallocate SM_Consign_DATANEXT


-----------------------------------------------------------------------

----------结转YYYYMMBILL=2的月结记录

	delete DETAILBILLFLOWTMP

	select @SQLSTR ='INSERT  INTO   DETAILBILLFLOWTMP Select * from  DETAILBILLFLOW where EQTY >0  AND YYYYMMBILL=2 and YYYYMM='

	select @SQLSTR =@SQLSTR+Char(39)+@Current_YYYYMM+Char(39)

	EXEC (@SQLSTR)


				
        update   DETAILBILLFLOWTMP  set YYYYMM=@Next_YYYYMM,StoreEqty=EQTY,STOREEPrice=Eprice,StoreEAMOUNT=EAMOUNT,INQTY=EQTY,INPRICE=EPRICE

	update   DETAILBILLFLOWTMP  set  ID = YYYYMM+GOODSID+BILLID+ITEMNO+CAST(BILLTYPE AS char(3))


	INSERT  INTO   DETAILBILLFLOW Select * from  DETAILBILLFLOWTMP



-----------------------------------------------------------------------
		SELECT @SQLSTR='	 select  distinct I.YYYYMM,I.GOODSID,I.STOREID,  '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0) as BQTY, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0) as MBQTY, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0) as BAMOUNT, ' --期初金额
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)+ isnull(E.INQTY,0) '
		SELECT @SQLSTR=@SQLSTR+'  as EQTY ,' --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0) '
		SELECT @SQLSTR=@SQLSTR+'  as MEQTY ,' --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0)  '
                           SELECT @SQLSTR=@SQLSTR+'  as EAMOUNT '--期初金额
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,STOREID,sum(INQTY*INOUTFLAG)  as INQTY ,sum(MINQTY*INOUTFLAG)  as MINQTY ,sum(INQTY*INOUTFLAG*INPRICE)  as INAMOUNT'             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM = '+char(39)+@Current_YYYYMM+char(39)                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID ,STOREID'
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID   AND  E.STOREID = I.STOREID '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,STOREID,sum(BQTY) as BQTY,sum(MBQTY) as MBQTY ,SUM(BAMOUNT)  AS BAMOUNT'
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM ='+char(39)+@Current_YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID,STOREID '	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID    AND  B.STOREID = I.STOREID'
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where   YYYYMM='+char(39)+@Current_YYYYMM+char(39)  +'  AND   YYYYMMBILL = 0'
		SELECT @SQLSTR=@SQLSTR+'          order by  I.GOODSID ,I.STOREID      '
                        DELETE   GOODSINITTMP
                       INSERT  INTO  GOODSINITTMP (YYYYMM,GOODSID,STOREID,BQTY,MBQTY,BAMOUNT,EQTY,MEQTY,EAMOUNT)   EXEC(@SQLSTR)
                      UPDATE  GOODSINITTMP SET YYYYMM=@Next_YYYYMM,BAMOUNT=EAMOUNT,BQTY=EQTY,MBQTY=MEQTY
                      UPDATE  GOODSINITTMP SET BQTY=0    where  BQTY is null
                      UPDATE  GOODSINITTMP SET MBQTY=0    where  MBQTY is null
                      UPDATE  GOODSINITTMP SET BPRICE = BAMOUNT/BQTY   WHERE  NOT (BQTY=0)
                      INSERT INTO GOODSINIT  
                                 SELECT *  FROM  GOODSINITTMP

------------------------------------------------------以上是接转仓库与货品，以下接转是客户的应收帐款的问题。


delete  CLIENTBILLFLOWTMP

		SELECT @SQLSTR='	 select  I.YYYYMM,I.CLIENTID,  YYYYMMBILL,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0) as BAMOUNT, ' --期初金额
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0)  '
                           SELECT @SQLSTR=@SQLSTR+'  as EAMOUNT '--期初金额
		 SELECT @SQLSTR=@SQLSTR+' from CLIENTBILLFLOW  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select CLIENTID,sum(INAMOUNT*INOUTFLAG)  as INAMOUNT  '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from CLIENTBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM = '+char(39)+@Current_YYYYMM+char(39)                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by CLIENTID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.CLIENTID = I.CLIENTID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select CLIENTID,SUM(BAMOUNT)  AS BAMOUNT'
		SELECT @SQLSTR=@SQLSTR+' from CLIENTBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM ='+char(39)+@Current_YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by CLIENTID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.CLIENTID = I.CLIENTID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where   YYYYMM='+char(39)+@Current_YYYYMM+char(39)  +'  AND   YYYYMMBILL = 0'
		SELECT @SQLSTR=@SQLSTR+'          order by  I.CLIENTID                '
------------------------------------------------------------------------

                       INSERT  INTO   CLIENTBILLFLOWTMP (YYYYMM,CLIENTID,YYYYMMBILL,BAMOUNT,EAMOUNT)   EXEC(@SQLSTR)


update   CLIENTBILLFLOWTMP  set YYYYMM=@Next_YYYYMM
update   CLIENTBILLFLOWTMP  set BAMOUNT=EAMOUNT


           ---定义游标解决插入的ID问题

    declare SM_Consign_CLIENT Cursor READ_ONLY for Select   YYYYMM,CLIENTID,YYYYMMBILL,BAMOUNT,EAMOUNT
						    from CLIENTBILLFLOWTMP 

    Open SM_Consign_CLIENT

    fetch SM_Consign_CLIENT into @YYYYMM,@CLIENTID,@YYYYMMBILL,@BAMOUNT,@EAMOUNT

    while @@fetch_status = 0            ----开始
    begin
             		    execute  GETKEYVALUE     'CLIENTBillFlow',@R_KeyValue = @NEWID output
		    insert into CLIENTBillFlow 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLCODE,CLIENTID,
		     BAMOUNT,     CACULATEFLAG,INOUTFLAG,EAMOUNT     )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillCode,@CLIENTID,
		     @BAMOUNT,    'F',@inoutFlag,@EAMOUNT    )    
    fetch SM_Consign_CLIENT into @YYYYMM,@CLIENTID,@YYYYMMBILL,@BAMOUNT,@EAMOUNT

    END           ------- SM_Consign_CLIENT  WHILE

    close SM_Consign_CLIENT
    deallocate SM_Consign_CLIENT

  update   accoptionS  set optionvalue=@Next_YYYYMM           where optionname ='YYYYMM'
     
------------------------------------------以下是接转供应商
delete  VENDORBILLFLOWTMP

		SELECT @SQLSTR='	 select  I.YYYYMM,I.VENDORID,  YYYYMMBILL,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0) as BAMOUNT, ' --期初金额
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0)  '
                           SELECT @SQLSTR=@SQLSTR+'  as EAMOUNT '--期初金额
		 SELECT @SQLSTR=@SQLSTR+' from VENDORBILLFLOW  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select VENDORID,sum(INAMOUNT*INOUTFLAG)  as INAMOUNT  '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from VENDORBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM = '+char(39)+@Current_YYYYMM+char(39)                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by VENDORID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.VENDORID = I.VENDORID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select VENDORID,SUM(BAMOUNT)  AS BAMOUNT'
		SELECT @SQLSTR=@SQLSTR+' from VENDORBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM ='+char(39)+@Current_YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by VENDORID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.VENDORID = I.VENDORID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where   YYYYMM='+char(39)+@Current_YYYYMM+char(39)  +'  AND   YYYYMMBILL = 0'
		SELECT @SQLSTR=@SQLSTR+'          order by  I.VENDORID                '
------------------------------------------------------------------------

                       INSERT  INTO   VENDORBILLFLOWTMP (YYYYMM,VENDORID,YYYYMMBILL,BAMOUNT,EAMOUNT)   EXEC(@SQLSTR)


update   VENDORBILLFLOWTMP  set YYYYMM=@Next_YYYYMM
update   VENDORBILLFLOWTMP  set BAMOUNT=EAMOUNT


           ---定义游标解决插入的ID问题

    declare SM_Consign_VENDOR Cursor  READ_ONLY for Select   YYYYMM,VENDORID,YYYYMMBILL,BAMOUNT,EAMOUNT
						    from VENDORBILLFLOWTMP 

    Open SM_Consign_VENDOR

    fetch SM_Consign_VENDOR into @YYYYMM,@VENDORID,@YYYYMMBILL,@BAMOUNT,@EAMOUNT

    while @@fetch_status = 0            ----开始
    begin
             		    execute  GETKEYVALUE     'VENDORBillFlow',@R_KeyValue = @NEWID output
		    insert into VENDORBillFlow 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLCODE,VENDORID,
		     BAMOUNT,     CACULATEFLAG,INOUTFLAG,EAMOUNT     )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillCode,@VENDORID,
		     @BAMOUNT,    'F',@inoutFlag,@EAMOUNT    )    
    fetch SM_Consign_VENDOR into @YYYYMM,@VENDORID,@YYYYMMBILL,@BAMOUNT,@EAMOUNT

    END           ------- SM_Consign_VENDOR  WHILE

    close SM_Consign_VENDOR
    deallocate SM_Consign_VENDOR
           ---定义游标解决插入的ID问题



------------------------------------------以下是接转运输单位
delete  YunShuDWBILLFLOWTMP

		SELECT @SQLSTR='	 select  I.YYYYMM,I.YunShuDWID,  YYYYMMBILL,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0) as BAMOUNT, ' --期初金额
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0)  '
                           SELECT @SQLSTR=@SQLSTR+'  as EAMOUNT '--期初金额
		 SELECT @SQLSTR=@SQLSTR+' from YunShuDWBILLFLOW  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select YunShuDWID,sum(INAMOUNT*INOUTFLAG)  as INAMOUNT  '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from YunShuDWBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM = '+char(39)+@Current_YYYYMM+char(39)                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by YunShuDWID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.YunShuDWID = I.YunShuDWID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select YunShuDWID,SUM(BAMOUNT)  AS BAMOUNT'
		SELECT @SQLSTR=@SQLSTR+' from YunShuDWBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM ='+char(39)+@Current_YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by YunShuDWID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.YunShuDWID = I.YunShuDWID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where   YYYYMM='+char(39)+@Current_YYYYMM+char(39)  +'  AND   YYYYMMBILL = 0'
		SELECT @SQLSTR=@SQLSTR+'          order by  I.YunShuDWID                '
------------------------------------------------------------------------

                       INSERT  INTO   YunShuDWBILLFLOWTMP (YYYYMM,YunShuDWID,YYYYMMBILL,BAMOUNT,EAMOUNT)   EXEC(@SQLSTR)


update   YunShuDWBILLFLOWTMP  set YYYYMM=@Next_YYYYMM
update   YunShuDWBILLFLOWTMP  set BAMOUNT=EAMOUNT


           ---定义游标解决插入的ID问题

    declare SM_Consign_YunShuDW Cursor  READ_ONLY for Select   YYYYMM,YunShuDWID,YYYYMMBILL,BAMOUNT,EAMOUNT
						    from YunShuDWBILLFLOWTMP 

    Open SM_Consign_YunShuDW

    fetch SM_Consign_YunShuDW into @YYYYMM,@YunShuDWID,@YYYYMMBILL,@BAMOUNT,@EAMOUNT

    while @@fetch_status = 0            ----开始
    begin
             		    execute  GETKEYVALUE     'YunShuDWBillFlow',@R_KeyValue = @NEWID output
		    insert into YunShuDWBillFlow 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLCODE,YunShuDWID,
		     BAMOUNT,     CACULATEFLAG,INOUTFLAG,EAMOUNT     )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillCode,@YunShuDWID,
		     @BAMOUNT,    'F',@inoutFlag,@EAMOUNT    )    
    fetch SM_Consign_YunShuDW into @YYYYMM,@YunShuDWID,@YYYYMMBILL,@BAMOUNT,@EAMOUNT

    END           ------- SM_Consign_YunShuDW  WHILE

    close SM_Consign_YunShuDW
    deallocate SM_Consign_YunShuDW
           ---定义游标解决插入的ID问题


------------------------------------------以下是接转银行帐目
delete  BANKBILLFLOWTMP

		SELECT @SQLSTR='	 select  I.YYYYMM,I.BANKID,  YYYYMMBILL,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0) as BAMOUNT, ' --期初金额
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0)  '
                           SELECT @SQLSTR=@SQLSTR+'  as EAMOUNT '--期初金额
		 SELECT @SQLSTR=@SQLSTR+' from BANKBILLFLOW  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select BANKID,sum(INAMOUNT*INOUTFLAG)  as INAMOUNT  '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from BANKBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM = '+char(39)+@Current_YYYYMM+char(39)                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by BANKID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.BANKID = I.BANKID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select BANKID,SUM(BAMOUNT)  AS BAMOUNT'
		SELECT @SQLSTR=@SQLSTR+' from BANKBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM ='+char(39)+@Current_YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by BANKID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.BANKID = I.BANKID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where   YYYYMM='+char(39)+@Current_YYYYMM+char(39)  +'  AND   YYYYMMBILL = 0'
		SELECT @SQLSTR=@SQLSTR+'          order by  I.BANKID                '
------------------------------------------------------------------------

                       INSERT  INTO   BANKBILLFLOWTMP (YYYYMM,BANKID,YYYYMMBILL,BAMOUNT,EAMOUNT)   EXEC(@SQLSTR)


update   BANKBILLFLOWTMP  set YYYYMM=@Next_YYYYMM
update   BANKBILLFLOWTMP  set BAMOUNT=EAMOUNT


           ---定义游标解决插入的ID问题

    declare SM_Consign_BANK Cursor READ_ONLY for Select   YYYYMM,BANKID,YYYYMMBILL,BAMOUNT,EAMOUNT
						    from BANKBILLFLOWTMP 

    Open SM_Consign_BANK

    fetch SM_Consign_BANK into @YYYYMM,@BANKID,@YYYYMMBILL,@BAMOUNT,@EAMOUNT

    while @@fetch_status = 0            ----开始
    begin
             		    execute  GETKEYVALUE     'BANKBillFlow',@R_KeyValue = @NEWID output
		    insert into BANKBillFlow 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLCODE,BANKID,
		     BAMOUNT,     CACULATEFLAG,INOUTFLAG,EAMOUNT     )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillCode,@BANKID,
		     @BAMOUNT,    'F',@inoutFlag,@EAMOUNT    )    
    fetch SM_Consign_BANK into @YYYYMM,@BANKID,@YYYYMMBILL,@BAMOUNT,@EAMOUNT

    END           ------- SM_Consign_BANK  WHILE

    close SM_Consign_BANK
    deallocate SM_Consign_BANK
           ---定义游标解决插入的ID问题

---------------------------------------处理下个月已经存在的业务进行重算
------2005.10.29加入

    declare SM_Consign_BANK_next Cursor for Select   BANKID    from BANKBILLFLOW   WHERE YYYYMMBILL=1  AND YYYYMM=@Next_YYYYMM

    Open SM_Consign_BANK_next

    fetch SM_Consign_BANK_next into   @BANKID

    while @@fetch_status = 0            ----开始
    begin
                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@Next_YYYYMM

    fetch SM_Consign_BANK_next into @BANKID

    END           ------- SM_Consign_BANK_next  WHILE

    close SM_Consign_BANK_next
    deallocate SM_Consign_BANK_next
           ---定义游标解决插入的ID问题

------------------------
    declare SM_Consign_VENDOR_next Cursor READ_ONLY for Select   VENDORID    from VENDORBILLFLOW   WHERE YYYYMMBILL=1  AND YYYYMM=@Next_YYYYMM

    Open SM_Consign_VENDOR_next

    fetch SM_Consign_VENDOR_next into   @VENDORID

    while @@fetch_status = 0            ----开始
    begin
                            execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@Next_YYYYMM

    fetch SM_Consign_VENDOR_next into @VENDORID

    END           ------- SM_Consign_VENDOR_next  WHILE

    close SM_Consign_VENDOR_next
    deallocate SM_Consign_VENDOR_next
           ---定义游标解决插入的ID问题

    declare SM_Consign_CLIENT_next Cursor for Select   CLIENTID    from CLIENTBILLFLOW   WHERE YYYYMMBILL=1  AND YYYYMM=@Next_YYYYMM

    Open SM_Consign_CLIENT_next

    fetch SM_Consign_CLIENT_next into   @CLIENTID

    while @@fetch_status = 0            ----开始
    begin
                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@Next_YYYYMM

    fetch SM_Consign_CLIENT_next into @CLIENTID

    END           ------- SM_Consign_CLIENT_next  WHILE

    close SM_Consign_CLIENT_next
    deallocate SM_Consign_CLIENT_next
           ---定义游标解决插入的ID问题
----------------------------------

	declare @STOREHSFS   INTEGER  --分仓核算

	       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           


    declare SM_GOODS_next Cursor for Select   GOODSID,STOREID    from   DETAILBILLFLOW   WHERE YYYYMMBILL=1  AND YYYYMM=@Next_YYYYMM  AND  CACULATEFLAG='T' 

    Open SM_GOODS_next

    fetch SM_GOODS_next into   @GOODSID,@STOREID

    while @@fetch_status = 0            ----开始
    begin
       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID

                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@Next_YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@Next_YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@Next_YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@Next_YYYYMM
				     END

                            END



    fetch SM_GOODS_next into   @GOODSID,@STOREID

    END           ------- SM_GOODS_next  WHILE

    close SM_GOODS_next
    deallocate SM_GOODS_next
           ---定义游标解决插入的ID问题
----------------------------------









-------------------2005.10.29

--------------------------------------

  update   accoptionS  set optionvalue=@Next_YYYYMM           where optionname ='YYYYMM'
     


--------取得接转当前会计期间的数据并复制到临时表中 end ------------------------------------

--写结转信息
  If @@error = 0
  begin
     commit transaction SMDataToNext
   set @IsSuccess=1
  end
  else
  begin
    rollback transaction SMDataToNext
   set @IsSuccess=0
    raiserror('结转失败 ', 1, 20) 
  end








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG
















CREATE PROCEDURE SM_DataToNextDel (
                              @Current_YYYYMM   varchar(20),   --传入当前会计期间
                              @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                              @IsSuccess         int output     ---返回成功  -- 0 不成功  --1 
                            )  --APSOFTENCRYPTION       WITH ENCRYPTION
 AS 
Begin transaction SMDataToNext

   declare  @PREV_YYYYMM          varchar(6)  -- 上一个会计年月
   declare  @GOODSID          varchar(10)  -- 上一个会计年月
   declare  @STOREID         varchar(10)  -- 上一个会计年月
   declare  @CLIENTID         varchar(10)  -- 上一个会计年月
   declare  @YunShuDWID         varchar(10)  -- 上一个会计年月
   declare  @VENDORID         varchar(10)  -- 上一个会计年月
   declare  @BANKID         varchar(10)  -- 上一个会计年月
   declare  @BILLID          varchar(10)  -- 上一个会计年月

      SET @RETURNSTRING='  '

	if substring(@Current_YYYYMM,5,2) = '01'  --- 如果当前会计月等于最大的会计月，将需要转入下年的的第一个会计年月
	begin
	    set @PREV_YYYYMM   = convert(varchar,convert(int,substring(@Current_YYYYMM,1,4))-1) +'12'  
	end
	else
	begin
	    set @PREV_YYYYMM   = substring(@Current_YYYYMM,1,4) +substring('00',1,2-len(convert(varchar,convert(int,substring(@Current_YYYYMM,5,2))-1)))+convert(varchar,convert(int,substring(@Current_YYYYMM,5,2))-1)
	end

		            IF  NOT  exists (select * from  DETAILBILLFLOW    where     YYYYMMBILL = 0  AND  YYYYMM =@PREV_YYYYMM  )
			BEGIN
			      rollback transaction SMDataToNext
			      set @IsSuccess = 0
                                              SET @RETURNSTRING='因为本会计期间是启用帐套的月份，不允许取消月末结帐'
                                          RETURN
			END

         	 DELETE  DETAILBILLFLOW  where YYYYMM=@Current_YYYYMM   and  YYYYMMBILL = 0   
  
         	 DELETE  DETAILBILLFLOW  where YYYYMM=@Current_YYYYMM   and  YYYYMMBILL = 2   AND len(ID)>10

	delete     GOODSINIT  where YYYYMM=@Current_YYYYMM   ---------这个不处理不影响数据
---------------------------------------------
		delete  CLIENTBILLFLOWTMP

		INSERT INTO  CLIENTBILLFLOWTMP   
	            select  * FROM CLIENTBILLFLOW  where YYYYMM=@Current_YYYYMM   and  YYYYMMBILL = 0   

		    declare CLIENT_Consign Cursor for   SELECT DISTINCT CLIENTID,BILLID FROM CLIENTBILLFLOWTMP 


		    Open CLIENT_Consign

		    fetch CLIENT_Consign into @CLIENTID,@BILLID

		    while @@fetch_status = 0            ----开始
		    begin
		            IF exists (select * from  CLIENTBILLFLOW where  CLIENTID=@CLIENTID  AND YYYYMMBILL = 0  AND  YYYYMM =@PREV_YYYYMM  )
		            BEGIN

		          	 DELETE  CLIENTBILLFLOW  where YYYYMM=@Current_YYYYMM   and  YYYYMMBILL = 0   AND   CLIENTID=@CLIENTID 

			END

		    fetch CLIENT_Consign into @CLIENTID,@BILLID

		    END           ------- CLIENT_Consign  WHILE

		    close CLIENT_Consign
		    deallocate CLIENT_Consign
  
-----------------------------------------
		delete  VENDORBILLFLOWTMP

		INSERT INTO  VENDORBILLFLOWTMP   
	            select  * FROM VENDORBILLFLOW  where YYYYMM=@Current_YYYYMM   and  YYYYMMBILL = 0   

		    declare VENDOR_Consign Cursor for   SELECT DISTINCT VENDORID,BILLID FROM VENDORBILLFLOWTMP 


		    Open VENDOR_Consign

		    fetch VENDOR_Consign into @VENDORID,@BILLID

		    while @@fetch_status = 0            ----开始
		    begin
		            IF exists (select * from  VENDORBILLFLOW where  VENDORID=@VENDORID  AND YYYYMMBILL = 0  AND  YYYYMM =@PREV_YYYYMM  )
		            BEGIN

		          	 DELETE  VENDORBILLFLOW  where YYYYMM=@Current_YYYYMM   and  YYYYMMBILL = 0   AND   VENDORID=@VENDORID 

			END

		    fetch VENDOR_Consign into @VENDORID,@BILLID

		    END           ------- VENDOR_Consign  WHILE

		    close VENDOR_Consign
		    deallocate VENDOR_Consign
  
-----------------------------------------

		delete  YunShuDWBILLFLOWTMP

		INSERT INTO  YunShuDWBILLFLOWTMP   
	            select  * FROM YunShuDWBILLFLOW  where YYYYMM=@Current_YYYYMM   and  YYYYMMBILL = 0   

		    declare YunShuDW_Consign Cursor for   SELECT DISTINCT YunShuDWID,BILLID FROM YunShuDWBILLFLOWTMP 


		    Open YunShuDW_Consign

		    fetch YunShuDW_Consign into @YunShuDWID,@BILLID

		    while @@fetch_status = 0            ----开始
		    begin
		            IF exists (select * from  YunShuDWBILLFLOW where  YunShuDWID=@YunShuDWID  AND YYYYMMBILL = 0  AND  YYYYMM =@PREV_YYYYMM  )
		            BEGIN

		          	 DELETE  YunShuDWBILLFLOW  where YYYYMM=@Current_YYYYMM   and  YYYYMMBILL = 0   AND   YunShuDWID=@YunShuDWID 

			END

		    fetch YunShuDW_Consign into @YunShuDWID,@BILLID

		    END           ------- YunShuDW_Consign  WHILE

		    close YunShuDW_Consign
		    deallocate YunShuDW_Consign


-----------------------------------------

		delete  BANKBILLFLOWTMP

		INSERT INTO  BANKBILLFLOWTMP   
	            select  * FROM BANKBILLFLOW  where YYYYMM=@Current_YYYYMM   and  YYYYMMBILL = 0   

		    declare BANK_Consign Cursor for   SELECT DISTINCT BANKID,BILLID FROM BANKBILLFLOWTMP 


		    Open BANK_Consign

		    fetch BANK_Consign into @BANKID,@BILLID

		    while @@fetch_status = 0            ----开始
		    begin
		            IF exists (select * from  BANKBILLFLOW where  BANKID=@BANKID  AND YYYYMMBILL = 0  AND  YYYYMM =@PREV_YYYYMM  )
		            BEGIN

		          	 DELETE  BANKBILLFLOW  where YYYYMM=@Current_YYYYMM   and  YYYYMMBILL = 0   AND   BANKID=@BANKID 

			END

		    fetch BANK_Consign into @BANKID,@BILLID

		    END           ------- BANK_Consign  WHILE

		    close BANK_Consign
		    deallocate BANK_Consign
  
  update   accoptionS  set optionvalue=@PREV_YYYYMM        where optionname ='YYYYMM'



--------取得接转当前会计期间的数据并复制到临时表中 end ------------------------------------

--写结转信息
  If @@error = 0
  begin
     commit transaction SMDataToNext
   set @IsSuccess=1
  end
  else
  begin
    rollback transaction SMDataToNext
   set @IsSuccess=0
    raiserror('结转失败 ', 1, 20) 
  end




----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














-------------------------------------------------------------------

CREATE PROCEDURE SM_Data_START (
                              @START_YYYYMM   varchar(20),   --传入当前会计期间
                              @START_YYYYMMDD  DATETIME,   --传入当前时间
                              @IsSuccess         int output     ---返回成功  -- 0 不成功  --1 
                            )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS 
Begin transaction SMDataToNext
   declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月
   declare  @SQLSTR         varchar(8000)  -- 下一个会计年月


declare @YYYYMM varchar(6)                   --会计年月     
declare @Current_YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。


declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)

declare @bill_type int           ---单据类型
declare @YYYYMMBILL int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @VENDORID varchar(15)               --明细存货编号
declare @CLIENTID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @Bqty NUMERIC(20,10)                          --数量
declare @BAMOUNT NUMERIC(20,10)                          --数量
declare @Eqty NUMERIC(20,10)                          --数量
declare @MEqty NUMERIC(20,10)                          --数量
declare @MBqty NUMERIC(20,10)                          --数量
declare @EAMOUNT NUMERIC(20,10)                          --数量
declare @BEGINAMOUNT NUMERIC(20,10)                          --数量

declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BANKID VARCHAR(25)
declare @YunShuDWID VARCHAR(25)
declare @BILLDATE DATEtime
declare @B_ID INTEGER
declare  @STATUS INTEGER
  


                 SELECT  @Current_YYYYMM='199912'
	    set @Next_YYYYMM   = @START_YYYYMM
         	SET @STATUS =(select   STATUS   FROM  ACCINFO  WHERE GUID='0001')
            IF  @STATUS=1                      ----已经启用帐套
             BEGIN
	     commit transaction SMDataToNext         
	   	   set @IsSuccess=1
	             RETURN
             END

--判断当前会计期间是否月结，不能重复月结



--------取得接转当前会计期间的数据并复制到临时表中 begin --------------------------------
delete  DETAILBILLFLOWTMP

		SELECT @SQLSTR='	 select DISTINCT I.YYYYMM,I.GOODSID,  I.STOREID,  INF_COSTINGTYPEID,YYYYMMBILL,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0) as BQTY, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0) as MBQTY, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0) as BAMOUNT, ' --期初金额
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)+ isnull(E.INQTY,0) '
		SELECT @SQLSTR=@SQLSTR+'  as EQTY ,' --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0) '
		SELECT @SQLSTR=@SQLSTR+'  as MEQTY ,' --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0)  '
                           SELECT @SQLSTR=@SQLSTR+'  as EAMOUNT '--期初金额
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,STOREID,sum(INQTY*INOUTFLAG)  as INQTY  ,sum(MINQTY*INOUTFLAG)  as MINQTY ,sum(INQTY*INOUTFLAG*INPRICE)  as INAMOUNT'             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM = '+char(39)+@Current_YYYYMM+char(39)                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID,STOREID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID    AND E.STOREID = I.STOREID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,STOREID,sum(BQTY) as BQTY ,sum(MBQTY) as MBQTY ,SUM(BAMOUNT)  AS BAMOUNT'
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM ='+char(39)+@Current_YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID,STOREID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID     AND B.STOREID = I.STOREID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where   YYYYMM='+char(39)+@Current_YYYYMM+char(39)  +'  AND   YYYYMMBILL = 0'
		SELECT @SQLSTR=@SQLSTR+'          order by  I.GOODSID,I.STOREID           '
------------------------------------------------------------------------

                       INSERT  INTO   DETAILBILLFLOWTMP (YYYYMM,GOODSID,STOREID,INF_COSTINGTYPEID,YYYYMMBILL,BQTY,MBQTY,BAMOUNT,EQTY,MEQTY,EAMOUNT)   EXEC(@SQLSTR)


update   DETAILBILLFLOWTMP  set YYYYMM=@Next_YYYYMM
update   DETAILBILLFLOWTMP  set BQTY=EQTY
update   DETAILBILLFLOWTMP  set MBQTY=MEQTY
update   DETAILBILLFLOWTMP  set BAMOUNT=EAMOUNT
           ---定义游标解决插入的ID问题

    declare SM_Consign_DATANEXT Cursor for Select   YYYYMM,GOODSID,STOREID,INF_COSTINGTYPEID,YYYYMMBILL,BQTY,MBQTY,BAMOUNT,EQTY,MEQTY,EAMOUNT
						    from DETAILBILLFLOWTMP 

    Open SM_Consign_DATANEXT

    fetch SM_Consign_DATANEXT into @YYYYMM,@GOODSID,@STOREID,@INF_COSTINGTYPEID,@YYYYMMBILL,@BQTY,@MBQTY,@BAMOUNT,@EQTY,@MEQTY,@EAMOUNT

    while @@fetch_status = 0            ----开始
    begin

             		    execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
		    insert into DetailBillFlow 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLCODE,ITEMNO,GOODSID,
		     BQTY,BPRICE,BAMOUNT,INQTY,INPRICE,OUTQTY,OUTPRICE,MBQTY,MEQTY,
		     EQTY,EPRICE,EAMOUNT,STOREID,CACULATEFLAG,INOUTFLAG,DIFAMOUNT,INF_COSTINGTYPEID,
		     BATCHREFID,REFQTY,REFCOUNT )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillCode,@itemNo,@GoodsID,
		     @BQTY,0,@BAMOUNT,0,0,Null,Null,@MBQTY,@MEQTY,
		     @EQTY,@price,@EAMOUNT,@StoreID,'F',@inoutFlag,null,@INF_COSTINGTYPEID,
		     @B_ID,0,0  )    
    fetch SM_Consign_DATANEXT into @YYYYMM,@GOODSID,@STOREID,@INF_COSTINGTYPEID,@YYYYMMBILL,@BQTY,@MBQTY,@BAMOUNT,@EQTY,@MEQTY,@EAMOUNT

    END           ------- SM_Consign_DATANEXT  WHILE

    close SM_Consign_DATANEXT
    deallocate SM_Consign_DATANEXT
-------------------------------------------------------------



----------结转YYYYMMBILL=2的月结记录

	delete DETAILBILLFLOWTMP

	select @SQLSTR ='INSERT  INTO   DETAILBILLFLOWTMP Select * from  DETAILBILLFLOW where EQTY >0  AND YYYYMMBILL=2 and YYYYMM='

	select @SQLSTR =@SQLSTR+Char(39)+@Current_YYYYMM+Char(39)

	EXEC (@SQLSTR)

        update   DETAILBILLFLOWTMP  set YYYYMM=@Next_YYYYMM,StoreEqty=EQTY,STOREEPrice=Eprice,StoreEAMOUNT=EAMOUNT,INQTY=EQTY,INPRICE=EPRICE

	update   DETAILBILLFLOWTMP  set  ID = YYYYMM+GOODSID+BILLID+ITEMNO+CAST(BILLTYPE AS char(3))



	INSERT  INTO   DETAILBILLFLOW Select * from  DETAILBILLFLOWTMP



-----------------------------------------------------------------------
		SELECT @SQLSTR='	 select  DISTINCT I.YYYYMM,I.GOODSID, I.STOREID, '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0) as BQTY, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0) as MBQTY, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0) as BAMOUNT, ' --期初金额
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)+ isnull(E.INQTY,0) '
		SELECT @SQLSTR=@SQLSTR+'  as EQTY ,' --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0) '
		SELECT @SQLSTR=@SQLSTR+'  as MEQTY ,' --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0)  '
                           SELECT @SQLSTR=@SQLSTR+'  as EAMOUNT '--期初金额
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,STOREID,sum(INQTY*INOUTFLAG)  as INQTY ,sum(MINQTY*INOUTFLAG)  as MINQTY  ,sum(INQTY*INOUTFLAG*INPRICE)  as INAMOUNT'             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM = '+char(39)+@Current_YYYYMM+char(39)                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID ,STOREID'
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID    AND  E.STOREID = I.STOREID '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,STOREID,sum(BQTY) as BQTY ,sum(MBQTY) as MBQTY,SUM(BAMOUNT)  AS BAMOUNT'
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM ='+char(39)+@Current_YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID,STOREID '	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID    AND  B.STOREID = I.STOREID '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where   YYYYMM='+char(39)+@Current_YYYYMM+char(39)  +'  AND   YYYYMMBILL = 0'
		SELECT @SQLSTR=@SQLSTR+'          order by  I.GOODSID,I.STOREID       '
                        DELETE   GOODSINITTMP
                       INSERT  INTO  GOODSINITTMP (YYYYMM,GOODSID,STOREID,BQTY,MBQTY,BAMOUNT,EQTY,MEQTY,EAMOUNT)   EXEC(@SQLSTR)
                      UPDATE  GOODSINITTMP SET YYYYMM=@START_YYYYMM,BAMOUNT=EAMOUNT,BQTY=EQTY,MBQTY=MEQTY
                      UPDATE  GOODSINITTMP SET BQTY=0    where  BQTY is null
                      UPDATE  GOODSINITTMP SET MBQTY=0    where  MBQTY is null
                      UPDATE  GOODSINITTMP SET BPRICE = BAMOUNT/BQTY   WHERE  NOT (BQTY=0)
                      INSERT INTO GOODSINIT  
                                 SELECT *  FROM  GOODSINITTMP
---------------------------------------以上是仓库初始化


    declare CLIENT_00 Cursor for Select   CLIENTID,BEGINAMOUNT from CLIENT 

    Open CLIENT_00

    fetch CLIENT_00 into   @CLIENTID,@BEGINAMOUNT
    while @@fetch_status = 0            ----开始
    begin

            IF   (not exists(select *  from CLIENTBILLFLOW  where 
             		                                    (rtrim(CLIENTID) = @CLIENTID)
                                        	      and(rtrim(YYYYMM) = @START_YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN

             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,'199912',1,@BillDate,@BillType,@CLIENTID,
		     0,@BEGINAMOUNT,Null,
		     1,@BEGINAMOUNT )    

             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@START_YYYYMM,0,@BillDate,@BillType,@CLIENTID,
		     @BEGINAMOUNT,0,Null,
		     1,@BEGINAMOUNT  )    
            END      ------IF   END
	    fetch CLIENT_00 into   @CLIENTID,@BEGINAMOUNT
       END

    close CLIENT_00
    deallocate CLIENT_00

----------------------------------------------------------------------------------
    declare VENDOR_00 Cursor for Select   VENDORID,BEGINAMOUNT from VENDOR 

    Open VENDOR_00

    fetch VENDOR_00 into   @VENDORID,@BEGINAMOUNT
    while @@fetch_status = 0            ----开始
    begin


            IF   (not exists(select *  from VENDORBILLFLOW  where 
             		                                    (rtrim(VENDORID) = @VENDORID)
                                        	      and(rtrim(YYYYMM) = @START_YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN
             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,'199912',1,@BillDate,@BillType,@VENDORID,
		     @BEGINAMOUNT,0,Null,
		     1,@BEGINAMOUNT  )    

             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@START_YYYYMM,0,@BillDate,@BillType,@VENDORID,
		     @BEGINAMOUNT,0,Null,
		     1,@BEGINAMOUNT  )    
            END      ------IF   END
-------------------------------增加应收帐款  是 INOUTFLAG为1
	    fetch VENDOR_00 into   @VENDORID,@BEGINAMOUNT
       END


    close VENDOR_00
    deallocate VENDOR_00

--------------------------------------

    declare BANK_00 Cursor for Select   BANKID,BEGINAMOUNT from BANK 

    Open BANK_00

    fetch BANK_00 into   @BANKID,@BEGINAMOUNT
    while @@fetch_status = 0            ----开始
    begin


            IF   (not exists(select *  from BANKBILLFLOW  where 
             		                                    (rtrim(BANKID) = @BANKID)
                                        	      and(rtrim(YYYYMM) = @START_YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,'199912',1,@BillDate,@BillType,@BANKID,
		     @BEGINAMOUNT,0,Null,
		     1,@BEGINAMOUNT  )    

             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@START_YYYYMM,0,@BillDate,@BillType,@BANKID,
		     @BEGINAMOUNT,0,Null,
		     1,@BEGINAMOUNT  )    
            END      ------IF   END
-------------------------------增加应收帐款  是 INOUTFLAG为1
	    fetch BANK_00 into   @BANKID,@BEGINAMOUNT
       END
--------------------------------------
    close BANK_00
    deallocate BANK_00


--------------------------------------

    declare YunShuDW_00 Cursor for Select   YunShuDWID,BEGINAMOUNT from YunShuDW 

    Open YunShuDW_00

    fetch YunShuDW_00 into   @YunShuDWID,@BEGINAMOUNT
    while @@fetch_status = 0            ----开始
    begin


            IF   (not exists(select *  from YunShuDWBILLFLOW  where 
             		                                    (rtrim(YunShuDWID) = @YunShuDWID)
                                        	      and(rtrim(YYYYMM) = @START_YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN
             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,'199912',1,@BillDate,@BillType,@YunShuDWID,
		     @BEGINAMOUNT,0,Null,
		     1,@BEGINAMOUNT  )    

             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@START_YYYYMM,0,@BillDate,@BillType,@YunShuDWID,
		     @BEGINAMOUNT,0,Null,
		     1,@BEGINAMOUNT  )    
            END      ------IF   END
-------------------------------增加应收帐款  是 INOUTFLAG为1
	    fetch YunShuDW_00 into   @YunShuDWID,@BEGINAMOUNT
       END
--------------------------------------
    close YunShuDW_00
    deallocate YunShuDW_00




  update   accoptionS  set optionvalue = @START_YYYYMM          where optionname ='YYYYMM'
  update   ACCINFO     set STARTDATE= @START_YYYYMMDD          where GUID ='0001'
  update   ACCINFO     set STATUS= 1          where GUID ='0001'
     



--------取得接转当前会计期间的数据并复制到临时表中 end ------------------------------------



--写结转信息
  If @@error = 0
  begin
     commit transaction SMDataToNext
   set @IsSuccess=1
  end
  else
  begin
    rollback transaction SMDataToNext
   set @IsSuccess=0
    raiserror('结转失败 ', 1, 20) 
  end









----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












--------------------------------------------------------------------
--------------------------------------------------------------------
----------------------------------
---------2005.07.20   修改过
--------------------------------------------------------------------
CREATE PROCEDURE [dbo].[STOREINOUTMXBREP](@STOREID varchar(8) ,                        -----如果为0000则全部仓库
                                                                                            @Begin_Date   varchar(10) ,
                                                                                           @End_date   varchar(10) ,  
						           @LCODE  varchar(10),             ---如果LCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSCODE  varchar(20),             ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSNAME  varchar(20),         ---如果GOODSNAME  为‘GGGG’表示不对类别进行查询
                                                                                           @INF_COSTINGTYPEID   smallint  ,    --------同价调拨标志   0  代表 不作为过滤条件
						           @modelNAME  varchar(20)             ---如果modelNAME  为‘GGGG’表示不对类别进行查询
                        
                                                      )   --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @end_dateAddone  datetime,
        @MAXBILLDATE  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8),
        @MAXYYYYMM   varchar(8),
        @WHERESTING   varchar(1800),
        @WHERESTING00   varchar(1800),
        @STOREIDSTR   varchar(100)

declare @GOODSCODE00   varchar(50)
declare @GOODSNAME00  varchar(50)

declare @ID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare  @BILLTYPE  INTEGER
declare @GOODSID  nvarchar(50)
declare @GOODSID00  nvarchar(50)
declare @BILLCODE  nvarchar(50)
declare @SPECNAME  nvarchar(50)
declare @BILLDATE  datetime
declare @BILLTYPENAME  nvarchar(50)
declare @UNIT  nvarchar(50) 
declare @INQTY  NUMERIC(20,10)
declare @INPRICE  NUMERIC(20,10)
declare @INAMOUNT NUMERIC(20,10)
declare @OUTQTY  NUMERIC(20,10)
declare @MOUTQTY  NUMERIC(20,10)
declare @MBQTY  NUMERIC(20,10)
declare @MINQTY  NUMERIC(20,10)
declare @MEQTY  NUMERIC(20,10)
declare @OUTPRICE  NUMERIC(20,10)
declare @OUTAMOUNT NUMERIC(20,10)
declare @EQTY NUMERIC(20,10)
declare @EPRICE NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @EQTYPREV NUMERIC(20,10)
declare @MEQTYPREV NUMERIC(20,10)
declare @EPRICEPREV NUMERIC(20,10)
declare @EAMOUNTPREV NUMERIC(20,10)
---//==========
declare @BQTY  NUMERIC(20,10)
declare @BPRICE  NUMERIC(20,10)
declare @BAMOUNT NUMERIC(20,10)
declare @MAXID  nvarchar(50)

                   set @now_date=(select   max(billDATE)   FROM detailbillflow)
--@WHERESTR='  and 1=1 '


                          
		if     NOT (@LCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = '  AND   GOODSID IN ( select GOODSID from  GOODS  where Lcode like '+CHAR(39)+@LCODE+'%'+CHAR(39)+ ')'
	                           SELECT    @WHERESTING00  = '  AND   GOODSID IN ( select GOODSID from  GOODS  where Lcode like '+CHAR(39)+@LCODE+'%'+CHAR(39)+ ')'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  ='     '
			SELECT    @WHERESTING00  ='     '
 		END
		print @WHERESTING
		if     NOT (@modelNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   GOODSID IN ( select  GOODSID from Goods   where  modelNAME LIKE   '+CHAR(39)+'%'+@modelNAME+'%'+CHAR(39)+ '  )'
	                           SELECT    @WHERESTING00  = @WHERESTING00+'  AND   GOODSID IN ( select  GOODSID from Goods   where  modelNAME LIKE   '+CHAR(39)+'%'+@modelNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
			SELECT    @WHERESTING00= @WHERESTING00+'     '
 		END
		if     NOT (@GOODSCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   GOODSID IN ( select  GOODSID from Goods   where  CODE LIKE   '+CHAR(39)+'%'+@GOODSCODE+'%'+CHAR(39)+ '  )'
	                           SELECT    @WHERESTING00  = @WHERESTING00+'  AND   GOODSID IN ( select  GOODSID from Goods   where  CODE LIKE   '+CHAR(39)+'%'+@GOODSCODE+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  =@WHERESTING+'     '
			SELECT    @WHERESTING00  =@WHERESTING00+'     '
 		END

                        SELECT    @WHERESTING  = @WHERESTING+'  AND     BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+ @End_date+char(39) 

		if     NOT (@GOODSNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   GOODSID IN ( select  GOODSID from Goods   where  NAME LIKE   '+CHAR(39)+'%'+@GOODSNAME+'%'+CHAR(39)+ '  )'
	                           SELECT    @WHERESTING00  = @WHERESTING00+'  AND   GOODSID IN ( select  GOODSID from Goods   where  NAME LIKE   '+CHAR(39)+'%'+@GOODSNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
			SELECT    @WHERESTING00= @WHERESTING00+'     '
 		END
		if     NOT (@INF_COSTINGTYPEID=0)
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND  GOODSID IN ( select  GOODSID from Goods   where INF_COSTINGTYPEID =  '+str(@INF_COSTINGTYPEID)+ '  )'
	                           SELECT    @WHERESTING00  = @WHERESTING00+'  AND  GOODSID IN ( select  GOODSID from Goods   where INF_COSTINGTYPEID =  '+str(@INF_COSTINGTYPEID)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
			SELECT    @WHERESTING00  = @WHERESTING00+'     '
 		END
	declare @STOREHSFS   INTEGER

	       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )      
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                           SELECT    @STOREIDSTR   = '  AND   STOREID =  '+char(39)+@STOREID+char(39)
                            END
                            IF   @STOREHSFS=0
                            BEGIN
	                           SELECT    @STOREIDSTR   = '          '
                            END
     

Create Table #temptable10
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   GOODSID  nvarchar(50)  NULL,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
   UNIT  nvarchar(50)  NULL,             
	[INQTY] NUMERIC(20,10)  NULL ,
	[INPRICE] NUMERIC(20,10)  NULL ,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTQTY] NUMERIC(20,10)  NULL ,
	[OUTPRICE] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EQTY] NUMERIC(20,10)  NULL ,
	[EPRICE] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
	[MINQTY] NUMERIC(20,10)  NULL ,
	[MOUTQTY] NUMERIC(20,10)  NULL ,
	[MEQTY]NUMERIC(20,10)  NULL 
		)

Create Table #temptable1
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   GOODSID  nvarchar(50)  NULL,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
   UNIT  nvarchar(50)  NULL,             
	[INQTY] NUMERIC(20,10)  NULL ,
	[INPRICE] NUMERIC(20,10)  NULL ,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTQTY] NUMERIC(20,10)  NULL ,
	[OUTPRICE] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EQTY] NUMERIC(20,10)  NULL ,
	[EPRICE] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
	[MINQTY] NUMERIC(20,10)  NULL ,
	[MOUTQTY] NUMERIC(20,10)  NULL ,
	[MEQTY]NUMERIC(20,10)  NULL 
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   ID , BILLID,BILLTYPE,GOODSID,BILLCODE,BILLDATE,BILLTYPE,BILLTYPE, INQTY  ,INPRICE,INQTY*INPRICE, '
           SELECT  @SQLSTR = @SQLSTR+' OUTQTY  ,OUTPRICE,OUTQTY*OUTPRICE,EQTY,EPRICE,EAMOUNT,MINQTY,MOUTQTY,MEQTY '
           SELECT  @SQLSTR = @SQLSTR+'  from detailbillflow   where yyyymmbill=1   and (INOUTFLAG = 1  OR INOUTFLAG = 0)'  + @WHERESTING +@STOREIDSTR
           SELECT  @SQLSTR = @SQLSTR+'  order by goodsid,id '  
            EXEC( @SQLSTR)
		print @SQLSTR
           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   ID , BILLID,BILLTYPE,GOODSID,BILLCODE,BILLDATE,BILLTYPE,BILLTYPE, NULL AS INQTY  ,NULL AS INPRICE,NULL , '
           SELECT  @SQLSTR = @SQLSTR+' INQTY  ,INPRICE,INQTY*INPRICE,EQTY,EPRICE,EAMOUNT ,NULL AS MINQTY,MINQTY,MEQTY '
           SELECT  @SQLSTR = @SQLSTR+'  from detailbillflow   where yyyymmbill=1   and INOUTFLAG = -1'  + @WHERESTING +@STOREIDSTR
           SELECT  @SQLSTR = @SQLSTR+'  order by goodsid,id '  
            EXEC( @SQLSTR)



----------------------------------------
Create Table #GOODSTMP
      (   GOODSID  nvarchar(50)  NULL
		)

Create Table #temptable2
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   GOODSID  nvarchar(50)  NULL,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
   UNIT  nvarchar(50)  NULL,
   SPECNAME  nvarchar(50)  NULL,
   SPECNAMED  nvarchar(50)  NULL,
	[INQTY] NUMERIC(20,10)  NULL ,
	[INPRICE] NUMERIC(20,10)  NULL ,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTQTY] NUMERIC(20,10)  NULL ,
	[OUTPRICE] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EQTY] NUMERIC(20,10)  NULL ,
	[EPRICE] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
	[MINQTY] NUMERIC(20,10)  NULL ,
	[MOUTQTY] NUMERIC(20,10)  NULL ,
	[MEQTY]NUMERIC(20,10)  NULL 
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (Select  ID,BILLID,BILLTYPE,GOODSID , BILLCODE,BILLDATE,BILLTYPENAME,
                                                      isnull(INQTY,0) as INqty,isnull(INPRICE,0) as INPRICE , isnull(INAMOUNT,0) as INAMOUNT ,
                                                     isnull(OUTQTY,0) as OUTqty,isnull(OUTPRICE,0) as OUTPRICE , isnull(OUTAMOUNT,0) as OUTAMOUNT ,
                                                    isnull(EQTY,0) as EQTY , isnull(EPRICE,0) as EPRICE , isnull(EAMOUNT,0) as EAMOUNT
	                  from  #temptable1        )
                 begin
	    declare INOUTMXBREP Cursor for Select  ID,BILLID,BILLTYPE,GOODSID , BILLCODE,BILLDATE,BILLTYPENAME,
                                                      isnull(INQTY,0) as INqty,isnull(INPRICE,0) as INPRICE , isnull(INAMOUNT,0) as INAMOUNT ,
                                                     isnull(OUTQTY,0) as OUTqty,isnull(OUTPRICE,0) as OUTPRICE , isnull(OUTAMOUNT,0) as OUTAMOUNT ,
                                                    isnull(EQTY,0) as EQTY , isnull(EPRICE,0) as EPRICE , isnull(EAMOUNT,0) as EAMOUNT, isnull(MINQTY,0) as  MINQTY, isnull(MOUTQTY,0) as  MOUTQTY, isnull(MEQTY,0) as  MEQTY
	                  from  #temptable1         ORDER BY  GOODSID,BILLDATE,ID

	    Open INOUTMXBREP

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE,@GOODSID , @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INqty,@INPRICE,@INAMOUNT,@OUTqty,@OUTPRICE,@OUTAMOUNT,@EQTY,@EPRICE,@EAMOUNT,@MINQTY,@MOUTQTY,@MEQTY

                 SELECT  @GOODSID00=@GOODSID
                 SELECT  @GOODSCODE00=CODE,@GOODSNAME00=NAME,@UNIT= UNIT ,@SPECNAME=SPECNAME  FROM GOODS  WHERE GOODSID=@GOODSID
                 SELECT  @GOODSCODE00='货品编码：'+@GOODSCODE00
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID,GOODSID , BILLCODE,BILLTYPENAME ,SPECNAME  ,UNIT      )
                                           VALUES  (@COUNTID,@GOODSID00 , @GOODSCODE00,@GOODSNAME00,@SPECNAME,@UNIT)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
                           select @MAXBILLDATE=MAX(BILLDATE) FROM detailbillflow   WHERE  GOODSID=@GOODSID  AND   STOREID=@STOREID   AND     BILLDATE  < @begin_date   AND YYYYMMBILL=1

			print @MAXBILLDATE

			if    @MAXBILLDATE is null
			begin
			SET  @BQTY=0
			SET  @MBQTY=0
			print '1111'
			SET  @BPRICE=0
			SET  @BAMOUNT=0
			end
			else
			begin
		                           SELECT  @MAXID=MAX(ID)  FROM detailbillflow  WHERE  GOODSID=@GOODSID  AND   STOREID=@STOREID   AND  BILLDATE=@MAXBILLDATE    AND YYYYMMBILL=1   ----  BILLDATE  < @begin_date
             		                            IF @MAXID IS NULL
 				BEGIN
				SET  @BQTY=0
				SET  @MBQTY=0
				SET  @BPRICE=0
				SET  @BAMOUNT=0
				END
                                        	ELSE
				BEGIN
		                           SELECT @BQTY=EQTY,@MBQTY=MEQTY,@BPRICE=EPRICE,@BAMOUNT=EAMOUNT   FROM   detailbillflow  WHERE ID=@MAXID
				END
			end
                            END
                            IF   @STOREHSFS=0
                            BEGIN
                           select @MAXBILLDATE=MAX(BILLDATE) FROM detailbillflow   WHERE  GOODSID=@GOODSID   AND     BILLDATE  < @begin_date  AND YYYYMMBILL=1
                           SELECT  @MAXID=MAX(ID)  FROM detailbillflow  WHERE  GOODSID=@GOODSID     AND  BILLDATE=@MAXBILLDATE  AND YYYYMMBILL=1  ----  BILLDATE  < @begin_date
                                         IF @MAXID IS NULL
 			BEGIN
			SET  @BQTY=0
			SET  @BPRICE=0
			SET  @MBQTY=0
			SET  @BAMOUNT=0
			END
                                        ELSE
			BEGIN
	                           SELECT @BQTY=EQTY,@MBQTY=MEQTY,@BPRICE=EPRICE,@BAMOUNT=EAMOUNT   FROM   detailbillflow  WHERE ID=@MAXID
			END
                            END
                                                              
                          INSERT    INTO   #temptable2  (ID,GOODSID , BILLTYPENAME,
                                                               EQTY,EPRICE,EAMOUNT,MEQTY)
                                           VALUES  (@COUNTID,@GOODSID00 , '期初结存',
                                                               @BQTY,@BPRICE,@BAMOUNT,@MBQTY)
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
                       SELECT  @BILLTYPENAME=NAME FROM  BILLNAME  WHERE @BILLTYPENAME=BILLTYPEID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
                      IF  @GOODSID00=@GOODSID
		BEGIN
                          INSERT    INTO   #temptable2  (ID,BILLID,BILLTYPE,GOODSID , BILLCODE,BILLDATE,BILLTYPENAME,UNIT,
                                                               INqty,INPRICE,INAMOUNT,OUTqty,OUTPRICE,OUTAMOUNT,EQTY,EPRICE,EAMOUNT,MINQTY,MOUTQTY,MEQTY)
                                           VALUES  (@COUNTID,@BILLID,@BILLTYPE,@GOODSID , @BILLCODE,@BILLDATE,@BILLTYPENAME,@UNIT,
                                                               @INqty,@INPRICE,@INAMOUNT,@OUTqty,@OUTPRICE,@OUTAMOUNT,@EQTY,@EPRICE,@EAMOUNT,@MINQTY,@MOUTQTY,@MEQTY)
                          END
                     ELSE
                          BEGIN

                          INSERT    INTO   #temptable2  (ID,GOODSID , BILLTYPENAME,
                                                               EQTY,EPRICE,EAMOUNT,MEQTY)
                                           VALUES  (@COUNTID,@GOODSID00 , '期末结存',
                                                              @EQTYPREV,@EPRICEPREV,@EAMOUNTPREV,@MEQTYPREV)
---------------------------------------------------------------
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID,GOODSID   )                  ----------插入空行
                                           VALUES  (@COUNTID,@GOODSID00 )
-------------------------------------------------------------------------------------------------------------------------------------------------------------
	                 SELECT @GOODSID00=@GOODSID
------------------------------------------------------
                 SELECT  @GOODSCODE00='货品编码：'+CODE,@GOODSNAME00=NAME,@UNIT= UNIT,@SPECNAME=SPECNAME   FROM GOODS  WHERE GOODSID=@GOODSID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID,GOODSID , BILLCODE,BILLTYPENAME ,SPECNAME,UNIT        )
                                           VALUES  (@COUNTID,@GOODSID00 , @GOODSCODE00,@GOODSNAME00,@SPECNAME,@UNIT)

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
                           select @MAXBILLDATE=MAX(BILLDATE) FROM detailbillflow   WHERE  GOODSID=@GOODSID  AND   STOREID=@STOREID   AND     BILLDATE  < @begin_date   AND YYYYMMBILL=1
		                           SELECT  @MAXID=MAX(ID)  FROM detailbillflow  WHERE  GOODSID=@GOODSID  AND   STOREID=@STOREID   AND  BILLDATE=@MAXBILLDATE    AND YYYYMMBILL=1   ----  BILLDATE  < @begin_date
             		                            IF @MAXID IS NULL
 				BEGIN
				SET  @BQTY=0
				SET  @MBQTY=0
				SET  @BPRICE=0
				SET  @BAMOUNT=0
				END
                                        	ELSE
				BEGIN
		                           SELECT @BQTY=EQTY,@MBQTY=MEQTY,@BPRICE=EPRICE,@BAMOUNT=EAMOUNT   FROM   detailbillflow  WHERE ID=@MAXID
				END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
                           select @MAXBILLDATE=MAX(BILLDATE) FROM detailbillflow   WHERE  GOODSID=@GOODSID   AND     BILLDATE  < @begin_date  AND YYYYMMBILL=1
                           SELECT  @MAXID=MAX(ID)  FROM detailbillflow  WHERE  GOODSID=@GOODSID     AND  BILLDATE=@MAXBILLDATE  AND YYYYMMBILL=1  ----  BILLDATE  < @begin_date
                                         IF @MAXID IS NULL
 			BEGIN
			SET  @BQTY=0
			SET  @MBQTY=0
			SET  @BPRICE=0
			SET  @BAMOUNT=0
			END
                                        ELSE
			BEGIN
	                           SELECT @BQTY=EQTY, @MBQTY=MEQTY,@BPRICE=EPRICE,@BAMOUNT=EAMOUNT   FROM   detailbillflow  WHERE ID=@MAXID
			END
                            END
                                                              
                          INSERT    INTO   #temptable2  (ID,GOODSID , BILLTYPENAME,
                                                               EQTY,EPRICE,EAMOUNT,MEQTY)
                                           VALUES  (@COUNTID,@GOODSID00 , '期初结存',
                                                               @BQTY,@BPRICE,@BAMOUNT,@MBQTY)

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
                          INSERT    INTO   #temptable2  (ID,BILLID,BILLTYPE,GOODSID , BILLCODE,BILLDATE,BILLTYPENAME,UNIT,
                                                               INqty,INPRICE,INAMOUNT,OUTqty,OUTPRICE,OUTAMOUNT,EQTY,EPRICE,EAMOUNT,MINQTY,MOUTQTY,MEQTY)
                                           VALUES  (@COUNTID,@BILLID,@BILLTYPE,@GOODSID , @BILLCODE,@BILLDATE,@BILLTYPENAME,@UNIT,
                                                               @INqty,@INPRICE,@INAMOUNT,@OUTqty,@OUTPRICE,@OUTAMOUNT,@EQTY,@EPRICE,@EAMOUNT,@MINQTY,@MOUTQTY,@MEQTY)
-------------------------------------------------

-----------------------------------------------------------------------
                          END
                       SET @EQTYPREV=@EQTY
                       SET @MEQTYPREV=@MEQTY
		SET    @EPRICEPREV=@EPRICE
 		    SET @EAMOUNTPREV=@EAMOUNT

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE,@GOODSID , @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INqty,@INPRICE,@INAMOUNT,@OUTqty,@OUTPRICE,@OUTAMOUNT,@EQTY,@EPRICE,@EAMOUNT,@MINQTY,@MOUTQTY,@MEQTY

	    END           ------- INOUTMXBREP  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID,GOODSID , BILLTYPENAME,
                                                               EQTY,EPRICE,EAMOUNT,MEQTY)
                                           VALUES  (@COUNTID,@GOODSID00 , '期末结存',
                                                              @EQTY,@EPRICE,@EAMOUNT,@MEQTY)

	    close INOUTMXBREP
	    deallocate INOUTMXBREP
        end     ------------  if exists
---------------------------
---------解决当前仓库本期间未发生业务的货品
--                  delete    #temptable1
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN       

		           SELECT  @SQLSTR = ' INSERT #GOODSTMP  '
		           SELECT  @SQLSTR = @SQLSTR+' SELECT DISTINCT GOODSID  FROM   detailbillflow  WHERE   (GOODSID  NOT IN (SELECT GOODSID  FROM   #temptable1 )  )  AND ( GOODSID  IN   (SELECT GOODSID  FROM detailbillflow  WHERE  EQTY <>0   ))  '+@WHERESTING00+ @STOREIDSTR
		            EXEC( @SQLSTR)
                                          
		    declare INOUTMXB Cursor for SELECT GOODSID  FROM   #GOODSTMP
		    Open INOUTMXB

		    fetch INOUTMXB into   @GOODSID

		    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
		    begin
					----------------应该取得月结记录
		                           select @MAXBILLDATE=MAX(BILLDATE) FROM detailbillflow   WHERE  GOODSID=@GOODSID  AND   STOREID=@STOREID   AND     BILLDATE  < =@begin_date   AND YYYYMMBILL=1

		                           SELECT  @ID=MAX(ID)  FROM detailbillflow  WHERE  GOODSID=@GOODSID  AND   STOREID=@STOREID      AND YYYYMMBILL=1  and  BILLDATE  = @MAXBILLDATE

             		                 INSERT  #temptable10  
	             		   SELECT      ID,NULL AS BILLID,NULL AS BILLTYPE, GOODSID,BILLCODE,BILLDATE,BILLTYPE,BILLTYPE, NULL AS INQTY  ,NULL AS INPRICE,NULL ,  
				 INQTY  ,INPRICE,INQTY*INPRICE, EQTY, EPRICE,  EAMOUNT,MINQTY,MOUTQTY,MEQTY
                          		      FROM   detailbillflow  WHERE    ID = @ID   
			    fetch INOUTMXB into   @GOODSID
             		     END
		    close INOUTMXB
		    deallocate INOUTMXB
                           END          ---------                      IF   @STOREHSFS=1    ---分仓库核算

                            IF   @STOREHSFS=0
                            BEGIN

		           SELECT  @SQLSTR = ' INSERT #GOODSTMP  '
		           SELECT  @SQLSTR = @SQLSTR+' SELECT DISTINCT GOODSID  FROM   detailbillflow  WHERE   (GOODSID  NOT IN (SELECT GOODSID  FROM   #temptable1 )  )  AND ( GOODSID  IN   (SELECT GOODSID  FROM detailbillflow  WHERE  EQTY <>0 ))  '+@WHERESTING00+ @STOREIDSTR
		            EXEC( @SQLSTR)
                                          
		    declare INOUTMXB Cursor for SELECT GOODSID  FROM   #GOODSTMP
		    Open INOUTMXB

		    fetch INOUTMXB into   @GOODSID

		    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
		    begin

		                           select @MAXBILLDATE=MAX(BILLDATE) FROM detailbillflow   WHERE  GOODSID=@GOODSID     AND     BILLDATE  < =@begin_date   AND YYYYMMBILL=1
		                           SELECT  @ID=MAX(ID)  FROM detailbillflow  WHERE  GOODSID=@GOODSID    AND YYYYMMBILL=1  and  BILLDATE  = @MAXBILLDATE
             		                 INSERT  #temptable10  
	             		   SELECT      ID,NULL AS BILLID,NULL AS BILLTYPE, GOODSID,BILLCODE,BILLDATE,BILLTYPE,BILLTYPE, NULL AS INQTY  ,NULL AS INPRICE,NULL ,  
				 INQTY  ,INPRICE,INQTY*INPRICE,EQTY,EPRICE,EAMOUNT,MINQTY,MOUTQTY,MEQTY
                          		      FROM   detailbillflow  WHERE    ID = @ID
			    fetch INOUTMXB into   @GOODSID
             		     END
		    close INOUTMXB
		    deallocate INOUTMXB
                            END
---------------------------------------------
	    declare INOUTMXBREP Cursor for Select  ID,BILLID,BILLTYPE,GOODSID , BILLCODE,BILLDATE,BILLTYPENAME,
                                                      isnull(INQTY,0) as INqty,isnull(INPRICE,0) as INPRICE , isnull(INAMOUNT,0) as INAMOUNT ,
                                                     isnull(OUTQTY,0) as OUTqty,isnull(OUTPRICE,0) as OUTPRICE , isnull(OUTAMOUNT,0) as OUTAMOUNT ,
                                                    isnull(EQTY,0) as EQTY , isnull(EPRICE,0) as EPRICE , isnull(EAMOUNT,0) as EAMOUNT, isnull(MINQTY,0) as  MINQTY, isnull(MOUTQTY,0) as  MOUTQTY, isnull(MEQTY,0) as  MEQTY
	                  from  #temptable10         ORDER BY  GOODSID,BILLDATE,ID

	    Open INOUTMXBREP

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE,@GOODSID , @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INqty,@INPRICE,@INAMOUNT,@OUTqty,@OUTPRICE,@OUTAMOUNT,@EQTY,@EPRICE,@EAMOUNT,@MINQTY,@MOUTQTY,@MEQTY

	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
                 SELECT  @GOODSID00=@GOODSID
                 SELECT  @GOODSCODE00=CODE,@GOODSNAME00=NAME,@UNIT= UNIT,@SPECNAME=SPECNAME   FROM GOODS  WHERE GOODSID=@GOODSID
                 SELECT  @GOODSCODE00='货品编码：'+@GOODSCODE00
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID,GOODSID , BILLCODE,BILLTYPENAME ,SPECNAME  ,UNIT      )
                                           VALUES  (@COUNTID,@GOODSID00 , @GOODSCODE00,@GOODSNAME00,@SPECNAME,@UNIT)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                                                              
                          INSERT    INTO   #temptable2  (ID,GOODSID , BILLTYPENAME,
                                                               EQTY,EPRICE,EAMOUNT,MEQTY)
                                           VALUES  (@COUNTID,@GOODSID00 , '期初结存',
                                                               @EQTY,@EPRICE,@EAMOUNT,@MEQTY)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
                          INSERT    INTO   #temptable2  (ID,GOODSID , BILLTYPENAME,
                                                               EQTY,EPRICE,EAMOUNT,MEQTY)
                                           VALUES  (@COUNTID,@GOODSID00 , '期末结存',
                                                              @EQTY,@EPRICE,@EAMOUNT,@MEQTY)

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID,GOODSID   )                  ----------插入空行
                                           VALUES  (@COUNTID,@GOODSID00 )
-------------------------------------------------------------------------------------------------------------------------------------------------------------

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE,@GOODSID , @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INqty,@INPRICE,@INAMOUNT,@OUTqty,@OUTPRICE,@OUTAMOUNT,@EQTY,@EPRICE,@EAMOUNT,@MINQTY,@MOUTQTY,@MEQTY


	    END           ------- INOUTMXBREP  WHILE

	    close INOUTMXBREP
	    deallocate INOUTMXBREP
---------------------------


--update a set a.字段=” from A a inner join B b on a.PId=b.FId where 条件
update #temptable2 set #temptable2.SPECNAMED=b.SPECNAMED from #temptable2 inner join VIEWXSCKGOODSCODE b on #temptable2.BILLID=b.BILLID and #temptable2.BILLtype=b.billtype

 SELECT ID, BILLID, BILLTYPE,    #temptable2.GOODSID ,   BILLCODE  ,   BILLDATE  ,   BILLTYPENAME ,  #temptable2.UNIT,#temptable2.SPECNAME,  #temptable2.SPECNAMED  ,INQTY,INPRICE,INAMOUNT,OUTQTY,OUTPRICE,	OUTAMOUNT,EQTY,EPRICE,EAMOUNT,#temptable2.MINQTY   AS MINQTY,#temptable2.MOUTQTY  as MOUTQTY ,#temptable2.MEQTY AS MEQTY
                           FROM #temptable2   ,GOODS   WHERE  #temptable2.GOODSID=GOODS.GOODSID    ORDER BY GOODS.CODE ,ID










----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG
























--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[STORELEDGER](@STOREID varchar(8) ,                        -----如果为0000则全部仓库
                                                                                           @YYYYMM  varchar(8),      --------为当前会计期间
						           @LCODE  varchar(10),             ---如果LCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSCODE  varchar(20),             ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSNAME  varchar(20),             ---如果GOODSNAME  为‘GGGG’表示不对类别进行查询
                                                           @INF_COSTINGTYPEID   smallint    ,  --------同价调拨标志   0  代表 不作为过滤条件
						           @modelNAME  varchar(20),             ---如果modelNAME  为‘GGGG’表示不对类别进行查询
                                                           @ZEROFLAG   smallint ,     --------同价调拨标志   0  代表 不作为过滤条件
						           @SPECNAME  varchar(20),             ---如果modelNAME  为‘GGGG’表示不对类别进行查询
						           @MAKEAREA  varchar(20) ,             ---如果modelNAME  为‘GGGG’表示不对类别进行查询
                                                           @StoreIDFlag   smallint     --------同价调拨标志   0  代表 不作为过滤条件


                         
                                                      )   --APSOFTENCRYPTION       WITH ENCRYPTION
as



Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @WHERESTING   varchar(1800),
        @STOREIDSTR   varchar(100),
        @DBSTING   varchar(100)
                   set @now_date=(select   max(billDATE)   FROM DETAILBILLFLOW)

--@WHERESTR='  and 1=1 '
		if     NOT (@LCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = '  AND   I.GOODSID IN ( select GOODSID from  GOODS  where Lcode like '+CHAR(39)+@LCODE+'%'+CHAR(39)+ ')'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  ='     '
 		END
		if     NOT (@GOODSCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  CODE LIKE   '+CHAR(39)+'%'+@GOODSCODE+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  =@WHERESTING+'     '
 		END
		if     NOT (@modelNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  modelNAME LIKE   '+CHAR(39)+'%'+@modelNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END

		if     NOT (@SpecName='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  SpecName LIKE   '+CHAR(39)+'%'+@SpecName+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END
		if     NOT (@MAKEAREA='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  MAKEAREA LIKE   '+CHAR(39)+'%'+@MAKEAREA+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END

		if     NOT (@GOODSNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  NAME LIKE   '+CHAR(39)+'%'+@GOODSNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END
		if     NOT (@INF_COSTINGTYPEID=0)
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where INF_COSTINGTYPEID =  '+str(@INF_COSTINGTYPEID)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END
		if     NOT (@STOREID='0000')
                BEGIN
	                           SELECT    @STOREIDSTR   = '  AND   STOREID =  '+CHAR(39)+@STOREID+CHAR(39)
                END
                ELSE
                BEGIN
			IF @StoreIDFlag=1 
        		BEGIN
		        	SELECT    @STOREIDSTR   = '  AND   STOREID NOT IN (select STOREID from Store where liuHFlag=1 or YuShouFlag=1) '
		        END
                	ELSE
	                BEGIN
			
				SELECT    @STOREIDSTR   = '     '
	 		END
 		END

------@StoreIDFlag=1  剔除留货仓库与预售仓库 

                       print   @WHERESTING


----------------------------------------------------
		---计算在途量

		delete  Store_GoodsID_ZaiTu

		INSERT INTO  Store_GoodsID_ZaiTu	select GoodsID ,StoreID,
			Sum(QuanTity)  as QuanTity ,Sum(unitqty) as Unitqty  from  VIEWGOODS_ZaiTu
			  group by GOODSID,StoreID
			  order by GoodsID,StoreID

----------------------------------------------------


Create Table #temptable10
      (GOODSID  varchar(10) primary key,
	  EQTY NUMERIC(20,10)  NULL, 
	  UNITQTY NUMERIC(20,10)  NULL, 
	  ZaiTuQuanTity NUMERIC(20,10)  NULL, 
	  ZaiTuUNITQTY NUMERIC(20,10)  NULL 
		)

----------------------------------------------------
		SELECT @SQLSTR='	 select  I.GOODSID,       '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)+ isnull(E.INQTY,0)  as EQTY, '   --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0)  as UNITQTY, '   --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(BXX.QuanTity,0) as ZaiTuQuanTity, isnull(BXX.UNITQTY,0)  as ZaiTuUNITQTY '   --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from Goods  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(INQTY*INOUTFLAG)  as INQTY  ,sum(MINQTY*INOUTFLAG)  as MINQTY '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)  +@STOREIDSTR                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(BQTY) as BQTY ,sum(MBQTY) as MBQTY '
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) +@STOREIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID  '
------------------------以上部分是取当前库存
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(QuanTity) as QuanTity ,sum(unitqty) as UNITQTY '
		SELECT @SQLSTR=@SQLSTR+' from Store_GoodsID_ZaiTu '
		SELECT @SQLSTR=@SQLSTR+' where 1=1  ' +@STOREIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as BXX on BXX.GOODSID = I.GOODSID  '

                SELECT @SQLSTR=@SQLSTR+'  where     I. GOODSID in (select GOODSID from DETAILBILLFLOW where YYYYMM >='+char(39)+@YYYYMM+char(39)+@STOREIDSTR+')'  + @WHERESTING 
		SELECT @SQLSTR=@SQLSTR+'          order by  I.CODE                '

		INSERT INTO  #temptable10  EXEC(@SQLSTR)


		IF  @ZEROFLAG=0
		BEGIN
			SELECT #temptable10.*,Goods.DSPRICE,Goods.MQTYSPRICE,Goods.DSPRICETax  FROM  #temptable10,Goods  WHERE #temptable10.GOODSID=GOODS.GOODSID AND #temptable10.UNITQTY <>0  ORDER BY GOODS.CODE
		END
		IF  @ZEROFLAG=1 
		BEGIN
			SELECT #temptable10.*,Goods.DSPRICE,Goods.MQTYSPRICE,Goods.DSPRICETax  FROM  #temptable10,Goods  WHERE #temptable10.GOODSID=GOODS.GOODSID   ORDER BY GOODS.CODE
		END





















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG

















--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------

CREATE PROCEDURE STORELEDGER_BJ(           @YYYYMM  varchar(8),     --------为当前会计期间
                         @Flag int
                                                      )    --APSOFTENCRYPTION       WITH ENCRYPTION
as



Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000)
---------------------------------------------------
Declare @KuCunBJType  varchar(10)

       SELECT    @KuCunBJType=(SELECT  KuCunBJType  FROM   ACCINFO    WHERE   GUID='0001' )           


CREATE TABLE #GOODSTMP (
	[GOODSID] [varchar] (25) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[TOPQTY] NUMERIC(20,10) NULL ,
	[DOWNQTY] NUMERIC(20,10) NULL ,
	[MEQTY] NUMERIC(20,10) NULL, 
	[EQTY] NUMERIC(20,10) NULL 
) ON [PRIMARY]

		SELECT @SQLSTR='	 select  I.GOODSID,   isnull(I.TOPQTY,0)    AS TOPQTY,isnull(I.DOWNQTY,0)    AS DOWNQTY,     '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0)  as MEQTY ,'   --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)+ isnull(E.INQTY,0)  as EQTY  '   --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from Goods  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(INQTY*INOUTFLAG)  as INQTY,sum(MINQTY*INOUTFLAG)  as MINQTY   '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)               --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(BQTY) as BQTY ,sum(MBQTY) as MBQTY'
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39)
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where     I. GOODSID in (select GOODSID from DETAILBILLFLOW where YYYYMM >='+char(39)+@YYYYMM+char(39)+')'  
--		SELECT @SQLSTR=@SQLSTR+'          order by  I.GOODSID                '
		SELECT @SQLSTR=@SQLSTR+'          order by  I.CODE                '
------------------------------------------------------------------------
	INSERT INTO   #GOODSTMP    EXEC(@SQLSTR)
	     IF @KuCunBJType = '数量' 
	     begin
		  IF @Flag=1	
		   begin
                   SELECT *  FROM #GOODSTMP   WHERE  MEQTY<DOWNQTY    AND (TOPQTY<>DOWNQTY )
		   end
		  IF @Flag=2	
		   begin
                   SELECT *  FROM #GOODSTMP   WHERE  MEQTY>TOPQTY    AND (TOPQTY<>DOWNQTY )
		   end
		  IF @Flag=3	
		   begin
                   SELECT *  FROM #GOODSTMP   WHERE  ( (MEQTY>TOPQTY)   OR  (MEQTY<DOWNQTY)   )  AND (TOPQTY<>DOWNQTY )
		   end
	     end
	     IF @KuCunBJType = '重量' 
	     begin
		  IF @Flag=1	
		   begin
                   SELECT *  FROM #GOODSTMP   WHERE  EQTY<DOWNQTY    AND (TOPQTY<>DOWNQTY )
		   end
		  IF @Flag=2	
		   begin
                   SELECT *  FROM #GOODSTMP   WHERE  EQTY>TOPQTY    AND (TOPQTY<>DOWNQTY )
		   end
		  IF @Flag=3	
		   begin
                   SELECT *  FROM #GOODSTMP   WHERE  ( (EQTY>TOPQTY)   OR  (EQTY<DOWNQTY)   )  AND (TOPQTY<>DOWNQTY )
		   end
	     end
	 
	
  		












----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG



















--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------

CREATE PROCEDURE STORELEDGER_BJ_Creat_CGDD(           @YYYYMM  varchar(8),     --------为当前会计期间
						      @sysdate   varchar(10),  
						      @MAKEMAN   varchar(10), 
                                                      @RETURNSTRING            varchar(60)    output       ---单据编号   
 
                                                      )    --APSOFTENCRYPTION       WITH ENCRYPTION
as



Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000)
---------------------------------------------------
Declare @KuCunBJType  varchar(10)
declare @ID   varchar(15)           
declare @BILLID00    varchar(15)           
declare @STOREID    varchar(15)           
declare @YYYYMM00    varchar(6)           
declare @BILLTYPE00    [int]     
declare @COUNT_MY    [int]     
declare @MAKEMAN00   [varchar] (50)   
declare @CODE00   [varchar] (25)   
declare 	@ITEMNO00    varchar (30) 
declare 	@TOPQTY NUMERIC(20,6)
declare 	@DOWNQTY NUMERIC(20,6) 
declare 	@UNITQTY NUMERIC(20,6)
declare 	@QUANTITY NUMERIC(20,6) 
declare 	@Rate NUMERIC(20,10) 
declare @GOODSID00    varchar(15)           


       SELECT    @KuCunBJType=(SELECT  KuCunBJType  FROM   ACCINFO    WHERE   GUID='0001' )           


CREATE TABLE #GOODSTMP (
	[GOODSID] [varchar] (25) COLLATE Chinese_PRC_CI_AS NOT NULL ,
	[TOPQTY] NUMERIC(20,10) NULL ,
	[DOWNQTY] NUMERIC(20,10) NULL ,
	[MEQTY] NUMERIC(20,10) NULL, 
	[EQTY] NUMERIC(20,10) NULL 
) ON [PRIMARY]

		SELECT @SQLSTR='	 select  I.GOODSID,   isnull(I.TOPQTY,0)    AS TOPQTY,isnull(I.DOWNQTY,0)    AS DOWNQTY,     '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0)  as MEQTY ,'   --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)+ isnull(E.INQTY,0)  as EQTY  '   --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from Goods  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(INQTY*INOUTFLAG)  as INQTY,sum(MINQTY*INOUTFLAG)  as MINQTY   '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)               --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(BQTY) as BQTY ,sum(MBQTY) as MBQTY'
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39)
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where     I. GOODSID in (select GOODSID from DETAILBILLFLOW where YYYYMM >='+char(39)+@YYYYMM+char(39)+')'  
--		SELECT @SQLSTR=@SQLSTR+'          order by  I.GOODSID                '
		SELECT @SQLSTR=@SQLSTR+'          order by  I.CODE                '
------------------------------------------------------------------------
	INSERT INTO   #GOODSTMP    EXEC(@SQLSTR)
	 

	     IF @KuCunBJType = '数量' 
	     begin
                 set  @COUNT_MY=( Select  Count(*)   FROM #GOODSTMP   WHERE  MEQTY<DOWNQTY    AND (TOPQTY<>DOWNQTY ))
	     end
	     IF @KuCunBJType = '重量' 
	     begin
                 set  @COUNT_MY=( Select  Count(*)    FROM #GOODSTMP   WHERE  EQTY<DOWNQTY    AND (TOPQTY<>DOWNQTY ))
	     end
		if @COUNT_MY=0 
		begin

		   set @RETURNSTRING='没有库存低的钢材，不能生成采购订单'
                       RETURN
		end
----------------------------------------------------------------------------------------------------------以下是插入主表
	
             		    execute  GET_BILL_NO     'STORECGDDM',@sysdate,'CD',@bill_no_selfd = @CODE00 output
             		    execute  GETKEYVALUE     'STORECGDDM',@R_KeyValue = @BILLID00 output

                           INSERT  INTO STORECGDDM   (BILLID,YYYYMM,CODE,MAKEMAN,BILLDATE,BILLTYPE)
                                      VALUES (@BILLID00,@YYYYMM,@CODE00,@MAKEMAN,@SYSDATE,103)
  		
----------------------------------------------------------------------以下是插入从表
----------------------------------------------------------------------以下是插入从表
	     IF @KuCunBJType = '数量' 
	     begin
                  declare SM_Consign_DATANEXT Cursor for Select   GOODSID,TOPQTY,DOWNQTY   FROM #GOODSTMP   WHERE  MEQTY<DOWNQTY    AND (TOPQTY<>DOWNQTY )
	     end
	     IF @KuCunBJType = '重量' 
	     begin
                  declare SM_Consign_DATANEXT Cursor for Select   GOODSID,TOPQTY,DOWNQTY    FROM #GOODSTMP   WHERE  EQTY<DOWNQTY    AND (TOPQTY<>DOWNQTY )
	     end


    Open SM_Consign_DATANEXT

    fetch SM_Consign_DATANEXT into @GOODSID00,@TOPQTY,@DOWNQTY

    while @@fetch_status = 0            ----开始
    begin
             		    execute  GETKEYVALUE     'STORECGDDD',@R_KeyValue = @ITEMNO00 output
	select @StoreID=(Select Storeid from goods where goodsid=@GOODSID00)

	Select Storeid from goods where storeid is null  OR len(storeid)<1

	 IF  @StoreID is null  OR len(@storeid)<1
	 begin
          select @StoreID=(Select top 1 Storeid from Store)
	 end	

        set @RATE =   (select ISNULL(RATE,0)*0.001  from GOODS where  GOODSID = @GOODSID00)


---------------根据理算系数核算重量与数量


	     IF @KuCunBJType = '数量' 
	     begin
		select @UNITQTY=(@TOPQTY+@DOWNQTY)/2
			IF @RATE<>0
			Begin
	   		 SELECT @QUANTITY=@RATE*@UNITQTY
			END	

	     end
	     IF @KuCunBJType = '重量' 
	     begin
		select @QUANTITY=(@TOPQTY+@DOWNQTY)/2
			IF @RATE<>0
			Begin
			   	 SELECT @UNITQTY=@QUANTITY/@RATE
			END	
	     end


		    insert into STORECGDDD 
		    (BILLID, ITEMNO,UNITQTY,STOREID,GOODSID,QUANTITY)
		    Values
		    (@BILLID00,@ITEMNO00 ,@UNITQTY,@STOREID,@GOODSID00 ,@QUANTITY)    

    fetch SM_Consign_DATANEXT into @GOODSID00,@TOPQTY,@DOWNQTY

    END           ------- SM_Consign_DATANEXT  WHILE

    close SM_Consign_DATANEXT
    deallocate SM_Consign_DATANEXT


   set @RETURNSTRING='成功生成采购订单，单号为'+@CODE00











----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














--------------------------------------------------------------------
--------------------------------------------------------------------2005.08.16
--------------------------------------------------------------------2005.09.02


CREATE PROCEDURE STORELEDGER_CRAET_PD(@STOREID varchar(8) ,                        -----如果为0000则全部仓库
                                                                                           @YYYYMM  varchar(8),      --------为当前会计期间
						           @sysdate   varchar(10),  
						           @MAKEMAN   varchar(10),  
						           @LCODE  varchar(10),             ---如果LCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSCODE  varchar(20),             ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSNAME  varchar(20),             ---如果GOODSNAME  为‘GGGG’表示不对类别进行查询
                                                                                           @INF_COSTINGTYPEID   smallint      --------同价调拨标志   0  代表 不作为过滤条件

                         
                                                      )    --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @WHERESTING   varchar(1800),
        @STOREIDSTR   varchar(100),
        @DBSTING   varchar(100)


declare @ID   varchar(15)           
declare @BILLID00    varchar(15)           
declare @YYYYMM00    varchar(6)           
declare @BILLTYPE00    [int]     
declare @MAKEMAN00   [varchar] (50)   
declare @CODE00   [varchar] (25)   
declare 	@ITEMNO00    varchar (30) 
declare @STOREID00    varchar(15)           
declare @VENDORID    varchar(15)           
declare @GOODSID00    varchar(15)           
declare	@APRICE00  NUMERIC(20,10) 
declare	@MEQTY  NUMERIC(20,10) 
declare	@QUANTITY00 NUMERIC(20,10)       --存放实际数量
declare	@PRICE00 NUMERIC(20,10)      ------存放帐面数量



                   set @now_date=(select   max(billDATE)   FROM DETAILBILLFLOW)

--@WHERESTR='  and 1=1 '
		if     NOT (@LCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = '  AND   I.GOODSID IN ( select GOODSID from  GOODS  where Lcode like '+CHAR(39)+@LCODE+'%'+CHAR(39)+ ')'

                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  ='     '
 		END
		if     NOT (@GOODSCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  CODE LIKE   '+CHAR(39)+'%'+@GOODSCODE+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  =@WHERESTING+'     '
 		END
		if     NOT (@GOODSNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  NAME LIKE   '+CHAR(39)+'%'+@GOODSNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END
		if     NOT (@INF_COSTINGTYPEID=0)
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where INF_COSTINGTYPEID =  '+str(@INF_COSTINGTYPEID)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'   '
 		END
                          SELECT    @STOREIDSTR   = '  AND  STOREID =  '+@STOREID

----------------------------------------------------

CREATE TABLE #LEDGER (
	[ID] [varchar] (25) COLLATE Chinese_PRC_CI_AS NULL ,
	[GOODSID] [varchar] (25) COLLATE Chinese_PRC_CI_AS NULL ,
	[STOREID] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,
	[INF_COSTINGTYPEID] [int] NULL ,
	[EQTY] NUMERIC(20,10) NULL, 
	[MEQTY] NUMERIC(20,10) NULL 
) ON [PRIMARY]

----------------------------------------------------
		SELECT @SQLSTR='	 select      NULL AS ID , I.GOODSID,   '+@STOREID+'    AS   STOREID, I.INF_COSTINGTYPEID ,    '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)+ isnull(E.INQTY,0)  as EQTY, '   --期末数量
		SELECT @SQLSTR=@SQLSTR+' ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0)  as MEQTY '   --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from Goods  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(INQTY*INOUTFLAG)  as INQTY,sum(MINQTY*INOUTFLAG)  as MINQTY  '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)  +@STOREIDSTR                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(BQTY) as BQTY , sum(MBQTY) as MBQTY '
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) +@STOREIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where  (  INF_COSTINGTYPEID  in (1,3,6) )   and   I. GOODSID in (select GOODSID from DETAILBILLFLOW where YYYYMM >='+char(39)+@YYYYMM+char(39)+@STOREIDSTR+')'  + @WHERESTING 
		SELECT @SQLSTR=@SQLSTR+'          order by  I.CODE                '
------------------------------------------------------------------------

		INSERT INTO   #LEDGER    EXEC(@SQLSTR)

                            DELETE    #LEDGER   WHERE EQTY=0

----------------------------------------------------------------------------------------------------------以下是插入主表
             		    execute  GET_BILL_NO     'STORECKPDM',@sysdate,'PD',@bill_no_selfd = @CODE00 output
             		    execute  GETKEYVALUE     'STORECKPDM',@R_KeyValue = @BILLID00 output

                           INSERT  INTO STORECKPDM   (BILLID,YYYYMM,CODE,MAKEMAN,BILLDATE,BILLTYPE)
                                      VALUES (@BILLID00,@YYYYMM,@CODE00,@MAKEMAN,@SYSDATE,6)
----------------------------------------------------------------------以下是插入从表
    declare SM_Consign_DATANEXT Cursor for Select   ID,GOODSID,EQTY,MEQTY   from #LEDGER

    Open SM_Consign_DATANEXT

    fetch SM_Consign_DATANEXT into @ID,@GOODSID00,@PRICE00,@MEQTY  

    while @@fetch_status = 0            ----开始
    begin
             		    execute  GETKEYVALUE     'STORECKPD',@R_KeyValue = @ITEMNO00 output
		    insert into STORECKPDD 
		    (BILLID, ITEMNO,PRICE,STOREID,GOODSID,REDETAILBILLFLOWID,UNITPRICE)
		    Values
		    (@BILLID00,@ITEMNO00 ,@PRICE00,@STOREID,@GOODSID00 ,@ID,@MEQTY)    

    fetch SM_Consign_DATANEXT into @ID,@GOODSID00,@PRICE00,@MEQTY  

    END           ------- SM_Consign_DATANEXT  WHILE

    close SM_Consign_DATANEXT
    deallocate SM_Consign_DATANEXT

----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












--------------------------------------------------------------------

CREATE PROCEDURE STORELEDGER_XIAN(@STOREID varchar(8) ,                        -----如果为0000则全部仓库
                                                           @YYYYMM  varchar(8),      --------为当前会计期间
						           @LCODE  varchar(10),             ---如果LCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSCODE  varchar(20),             ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSNAME  varchar(20),             ---如果GOODSNAME  为‘GGGG’表示不对类别进行查询
						           @SpecName  varchar(20),             ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
						           @ModelNAME  varchar(20)             ---如果GOODSNAME  为‘GGGG’表示不对类别进行查询
                        
                                                      )   --APSOFTENCRYPTION       WITH ENCRYPTION
as



Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @WHERESTING   varchar(1800),
        @STOREIDSTR   varchar(100),
        @DBSTING   varchar(100)
                   set @now_date=(select   max(billDATE)   FROM DETAILBILLFLOW)

--@WHERESTR='  and 1=1 '
		if     NOT (@LCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = '  AND   I.GOODSID IN ( select G.GOODSID from GoodsTypetree T, GOODS G where T.indirect_no = '+CHAR(39)+@LCODE+CHAR(39)+ '  AND T.self_no=G.LCODE )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  ='     '
 		END
		if     NOT (@GOODSCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  CODE LIKE   '+CHAR(39)+'%'+@GOODSCODE+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  =@WHERESTING+'     '
 		END
		if     NOT (@GOODSNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  NAME LIKE   '+CHAR(39)+'%'+@GOODSNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END

		if     NOT (@SpecName='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  NAME LIKE   '+CHAR(39)+'%'+@SpecName+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END

		if     NOT (@ModelName='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  NAME LIKE   '+CHAR(39)+'%'+@ModelName+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END


		if     NOT (@STOREID='0000')
                           BEGIN
	                           SELECT    @STOREIDSTR   = '  AND   STOREID =  '+CHAR(39)+@STOREID+CHAR(39)
                           END
                           ELSE
                           BEGIN
			SELECT    @STOREIDSTR   = '     '
 		END
----------------------------------------------------


Create Table #temptable10
      (GOODSID  varchar(10) ,
	    CODE  varchar(30) ,
	  EQTY NUMERIC(20,6)  NULL, 
	  MEQTY NUMERIC(20,6)  NULL, 
	  EPRICE NUMERIC(20,6)  NULL, 
	  EAMOUNT NUMERIC(20,2)  NULL 
		)

----------------------------------------------------
----------------------------------------------------
		SELECT @SQLSTR='	 select  I.GOODSID, I.CODE,      '
		SELECT @SQLSTR=@SQLSTR+' E.EQTY,E.MEQTY,E.EPRICE,E.EAMOUNT '   --期末数量
		SELECT @SQLSTR=@SQLSTR+' from Goods  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,EQTY,MEQTY,EPRICE,EAMOUNT '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 2    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)  +@STOREIDSTR                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID  '
------------------------以上部分是取当前库存
                SELECT @SQLSTR=@SQLSTR+'  where     I. GOODSID in (select GOODSID from DETAILBILLFLOW where YYYYMM >='+char(39)+@YYYYMM+char(39)+@STOREIDSTR+')'  + @WHERESTING 
		SELECT @SQLSTR=@SQLSTR+'          order by  I.CODE                '
------------------------------------------------------------------------

		INSERT INTO  #temptable10  EXEC(@SQLSTR)

			SELECT GOODSID,EQTY,EPRICE,EAMOUNT,MEQTY  FROM  #temptable10   WHERE   EQTY <>0  ORDER BY CODE 











----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG
















--------------------------------------------------------------------
--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[STOREYYYYMMDD](@STOREID varchar(8) ,                        -----如果为0000则全部仓库
                                                                                            @Begin_Date   varchar(10) ,
                                                                                           @End_date   varchar(10) ,  
                                                                                           @YYYYMM  varchar(8),      --------为当前会计期间
                                                                                           @DBFLAG  int ,     --------同价调拨标志   1代表包含  0 代表不包含
						           @LCODE  varchar(10),             ---如果LCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSCODE  varchar(20),             ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSNAME  varchar(20),             ---如果GOODSNAME  为‘GGGG’表示不对类别进行查询
                                                                                           @INF_COSTINGTYPEID   smallint ,     --------同价调拨标志   0  代表 不作为过滤条件
						           @modelNAME  varchar(20)             ---如果modelNAME  为‘GGGG’表示不对类别进行查询

                         
                                                      )     --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @WHERESTING   varchar(1800),
        @STOREIDSTR   varchar(100),
        @DBSTING   varchar(100)
                   set @now_date=(select   max(billDATE)   FROM DETAILBILLFLOW)
		
		IF @now_date IS NULL
		BEGIN
			SET @now_date='2030-12-12'
		END

--@WHERESTR='  and 1=1 '
                SELECT @DBSTING = '        '
		if     NOT (@LCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = '  AND   I.GOODSID IN ( select GOODSID from  GOODS  where Lcode like '+CHAR(39)+@LCODE+'%'+CHAR(39)+ ')'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  ='     '
 		END
		if     NOT (@modelNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  modelNAME LIKE   '+CHAR(39)+'%'+@modelNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END
		if     NOT (@GOODSCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  CODE LIKE   '+CHAR(39)+'%'+@GOODSCODE+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  =@WHERESTING+'     '
 		END
		if     NOT (@GOODSNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  NAME LIKE   '+CHAR(39)+'%'+@GOODSNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END
		if     NOT (@INF_COSTINGTYPEID=0)
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where INF_COSTINGTYPEID =  '+str(@INF_COSTINGTYPEID)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END
		if     NOT (@STOREID='0000')
                           BEGIN
	                           SELECT    @STOREIDSTR   = '  AND   STOREID =  '+CHAR(39)+@STOREID +CHAR(39)
                      		           select  @DBSTING   =@DBSTING+'      '                                             
                           END
                           ELSE
                           BEGIN
			SELECT    @STOREIDSTR   = '     '
	                         IF @DBFLAG=1
			BEGIN
                          		           select  @DBSTING   =@DBSTING+'   '                                             
			END
	                         IF @DBFLAG=0
			BEGIN
                          		           select  @DBSTING   =@DBSTING+'    AND    (not (BILLTYPE=5))  '   ---剔除调拨单
			END
 		END

----------------------------------------------------
		SELECT @SQLSTR='	 select  I.GOODSID, I.MQTYSPRICE,I.DSPRICETax,      '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)+ isnull(E.INQTY,0) -(isnull(BN.INQTY,0)- isnull(BN00.INQTY,0)) as BQTY, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0) -(isnull(BN.MINQTY,0)- isnull(BN00.MINQTY,0)) as MBQTY, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0) -(isnull(BN.INAMOUNT,0)- isnull(BN00.INAMOUNT,0)) as BAMOUNT, ' --期初金额
		SELECT @SQLSTR=@SQLSTR+'ISNULL(BE.INQTY,0)  AS INQTY   ,ISNULL(BE00.INQTY,0)  AS OUTQTY,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(BE.MINQTY,0)  AS MINQTY   ,ISNULL(BE00.MINQTY,0)  AS MOUTQTY,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(BE.INAMOUNT,0)  AS INAMOUNT  ,ISNULL(BE00.INAMOUNT,0)  AS OUTAMOUNT,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)+ isnull(E.INQTY,0) -(isnull(BN.INQTY,0)- isnull(BN00.INQTY,0))'
		SELECT @SQLSTR=@SQLSTR+'+ isnull(BE.INQTY,0)-isnull(BE00.INQTY,0) as EQTY ,' --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0) -(isnull(BN.MINQTY,0)- isnull(BN00.MINQTY,0))'
		SELECT @SQLSTR=@SQLSTR+'+ isnull(BE.MINQTY,0)-isnull(BE00.MINQTY,0) as MEQTY ,' --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0) -(isnull(BN.INAMOUNT,0)- isnull(BN00.INAMOUNT,0)) '
                           SELECT @SQLSTR=@SQLSTR+'+ISNULL(BE.INAMOUNT,0)-ISNULL(BE00.INAMOUNT,0)       as EAMOUNT '--期初金额
		 SELECT @SQLSTR=@SQLSTR+' from Goods  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(INQTY*INOUTFLAG)  as INQTY ,sum(MINQTY*INOUTFLAG)  as MINQTY ,sum(round(INQTY*INOUTFLAG*INPRICE,2))  as INAMOUNT'             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)  +@STOREIDSTR                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(BQTY) as BQTY ,sum(MBQTY) as MBQTY,SUM(BAMOUNT)  AS BAMOUNT'
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) +@STOREIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID  '
------------------------以上部分是取当前库存
		SELECT @SQLSTR=@SQLSTR+'  left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(INQTY) as INQTY ,sum(MINQTY) as MINQTY  ,sum(round(INQTY*INPRICE,2))  as INAMOUNT      '
		SELECT @SQLSTR=@SQLSTR+'  from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+ @Now_Date+char(39) +'  AND INOUTFLAG =1'  +@DBSTING +@STOREIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as BN on BN.GOODSID = I.GOODSID'  
		SELECT @SQLSTR=@SQLSTR+'  left outer join '
		SELECT @SQLSTR=@SQLSTR+'  (  '
		SELECT @SQLSTR=@SQLSTR+'select GOODSID,sum(INQTY) as INQTY ,sum(MINQTY) as MINQTY   ,sum(round(INQTY*INPRICE,2))  as INAMOUNT      '
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+ @Now_Date +char(39) +' AND INOUTFLAG =-1 '  +@DBSTING +@STOREIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BN00 on BN00.GOODSID = I.GOODSID  '
------------------------以上部分为取begin_date到Now_Date的库存
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(INQTY) as INQTY  ,sum(MINQTY) as MINQTY ,sum(round(INQTY*INPRICE,2))  as INAMOUNT      '
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+@End_Date+char(39)+' AND INOUTFLAG =1 ' +@DBSTING +@STOREIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE on BE.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(INQTY) as INQTY ,sum(MINQTY) as MINQTY  ,sum(round(INQTY*INPRICE,2))  as INAMOUNT      '
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+@End_Date +char(39)+'AND INOUTFLAG =-1'  +@DBSTING +@STOREIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE00 on BE00.GOODSID = I.GOODSID  '
                          SELECT @SQLSTR=@SQLSTR+'  where     I. GOODSID in (select GOODSID from DETAILBILLFLOW where YYYYMM >='+char(39)+@YYYYMM+char(39)+@STOREIDSTR+')'  + @WHERESTING 
		SELECT @SQLSTR=@SQLSTR+'          order by  I.CODE                '   
------------------------------------------------------------------------
		EXEC(@SQLSTR)


----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG

































----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_CGDD]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @VENDORFlag int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ITEMNO varchar(15)               --明细存货编号
declare @YunShuDWID varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号、
declare @VENDORID varchar(15)               --明细存货编号、
declare @INStoreID varchar(15)               --明细存货编号、
declare @SUMAMT  NUMERIC(20,10)               --明细存货编号、
declare @RATE  NUMERIC(20,10)               --明细存货编号、
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @STOREIDEqty NUMERIC(20,10)                          --仓库数量
declare @REFqty NUMERIC(20,10)                          --数量
declare @UNITqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @PRICETYPE  NUMERIC(20,10)               --含税单价
declare @KEYONGQTY  NUMERIC(20,10)               --含税单价
declare @TAXRATE NUMERIC(20,10)               --含税单价
declare @APRICE  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID  varchar(50)
declare @GOODSNAME varchar(30)                     --序列号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @REITEMNO VARCHAR(25)
declare @BILLDATE DATEtime
declare @SFLAG  INTEGER
declare @YYYYMM_FLAG  INTEGER
declare @count  INTEGER
declare @MaxRate  NUMERIC(20,10)               --含税单价
declare @MinRate  NUMERIC(20,10)               --含税单价
declare @DMinSPrice NUMERIC(20,10)               --含税单价

declare @STOREHSFS   INTEGER
declare @ZhongLiangXZ   INTEGER
declare @XSPriceXZ   INTEGER
declare @NEGCLOSEOFF   bit
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @JianShu [int] 
declare @MeiJianQty [T_QUANTITY] 
declare @LingTou [T_QUANTITY] 

       SELECT    @NEGCLOSEOFF=(SELECT  NEGCLOSEOFF  FROM   ACCINFO    WHERE   GUID='0001' )           

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )  
         


set @BILLID   = ltrim(rtrim(@BILLID))
SET  @RETURNSTRING='  '
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @ZhongLiangXZ   = (select optionvalue from accoptions where optionname ='ZhongLiangXZ')     
     set @XSPriceXZ   = (select optionvalue from accoptions where optionname ='XSPriceXZ')     

     set @BillDate =   (select BillDate  from STORECGDDM where rtrim(BILLID) = @BILLID)

    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 


      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END


if  (select isnull(flagPost,0) from STORECGDDM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CGDD   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STORECGDDM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STORECGDDM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STORECGDDM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STORECGDDM where rtrim(BILLID) = @BILLID)
     set @VENDORID =   (select VENDORID  from STORECGDDM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STORECGDDM where rtrim(BILLID) = @BILLID)
-----------@SFLAG  是否留货 1为留货
     set @INStoreID =   (select PAYTYPEID  from  STORECGDDM where rtrim(BILLID) = @BILLID)   ---------收款银行

     set @VENDORFLAG =   (select  ISNULL(VENDORFLAG,1)   from STORECGDDM where rtrim(BILLID) = @BILLID)


   	 SELECT @SUMAMT= (SELECT SUM(ROUND(DISC*0.01*unitprice*UNITQTY*(1+ISNULL(TAXRATE,0)*0.01),2)) FROM   STORECGDDD  where rtrim(BILLID) = @BILLID)
   	 SELECT @SUMAMT=0


                                      IF NOT (exists (select * from ViewVENDOR where VENDORID=@VENDORID   and VENDORFLAG=@VENDORFLAG))
                                     BEGIN
			      rollback transaction  trans_CGDD 
			      set @flagreturn = 0
                                              SET @RETURNSTRING='供应商不能为空或供应商不存在，单据不能记帐'
                                          RETURN
			END


   update  STORECGDDM  set  flagPost = 1,YYYYMM =@BILLYYYYMM   ,SUMAMT=VendorHKSum ,INVOICEAMT=0  ,STATUS=0        where ltrim(rtrim(BILLID)) = @BILLID 
   update  STORECGDDD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)          where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STORECGDDD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)   where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CGDD
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CGDD
      set @flagreturn = 0
   end
end

----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG

























----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_CGDD_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare  @INF_COSTINGTYPEID  INT
declare  @VENDORFlag  INT
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @VENDORID varchar(10)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @ChaCheSID VARCHAR(25)
declare @INSTOREID    varchar(15)               --明细存货编号

declare @STOREID    varchar(15)               --明细存货编号
declare @REDetailBillFlowID   varchar(30)                     --序列号
declare @REITEMNO   varchar(30)                     --序列号
declare @QUANTITY   NUMERIC(20,10)                     --序列号
declare @STATUS INT
declare @UNITQTY   NUMERIC(20,10)                     --序列号
declare @BILLTYPE   INTEGER
declare @SFLAG   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

                                              SET @RETURNSTRING='   '


	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STORECGDDM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STORECGDDM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CGDD_DEL   --事物开始

     set @BillType =   (select BillType  from STORECGDDM where rtrim(BILLID) = @BILLID)
     set @INStoreID =   (select PAYTYPEID  from  STORECGDDM where rtrim(BILLID) = @BILLID)   ---------收款银行
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STORECGDDM where rtrim(BILLID) = @BILLID)
	     set @STATUS =   (select  ISNULL(STATUS,0)  from STORECGDDM where rtrim(BILLID) = @BILLID)

			IF exists(select *  FROM  STORECGRKM  where rtrim(BILLID) = @BILLID   AND SUBSTRING(@BILLID,1,2)='CD')
			BEGIN
                              SET @RETURNSTRING=' 此订单已经被采购入库单引用不能取消记帐  '
			      rollback transaction trans_CGDD_DEL
			      set @flagreturn = 0
                                         RETURN
			END


			IF   @STATUS=1  
             		             BEGIN
                                              SET @RETURNSTRING=' 此订单已经完成不能取消记帐  '
			      rollback transaction trans_CGDD_DEL
			      set @flagreturn = 0
                                         RETURN
			END

			----如果订单已经被引用则不能取消记帐





   update  STORECGDDM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CGDD_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CGDD_DEL
      set @flagreturn = 0
   end
end
















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[STORE_CGFK]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @REBILLID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @REBILLTYPE int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。


declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)

declare @bill_type int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @BANKID varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @VENDORID   varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @CLIENTID varchar(15)               --明细存货编号
declare @qty NUMERIC(20, 8)                          --数量
declare @SUMAMT NUMERIC(20, 8)                          --数量
declare @refqty NUMERIC(20, 8)                          --数量
declare @PRICE  NUMERIC(20, 8)               --含税单价
declare @AMT  NUMERIC(20, 8)               --含税单价
declare @MianAMT  NUMERIC(20, 8)               --含税单价
declare @VendorFLAG  int                    ---是否现款标志

declare @BATCHCODE varchar(30)                     --序列号
declare @VALIDDATE DATEtime



declare @BILLTYPE INTEGER

declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @MINBILLDATE DATEtime
declare @MAXBILLDATE DATEtime
declare @PRODUCTDATE DATEtime
declare @B_CODE VARCHAR(25)
declare @V_DATE DATEtime
declare @B_ID INTEGER
declare @SFKTYPE INTEGER
declare @STOREHSFS   INTEGER
declare @YYYYMM_FLAG  INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

   declare  @PREV_YYYYMM          varchar(6)  -- 上一个会计年月
   declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     

     set @BillDate =   (select BillDate  from STORECGFKM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END



if  (select isnull(flagPost,0) from STORECGFKM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CGFK   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STORECGFKM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STORECGFKM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STORECGFKM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STORECGFKM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  SFLAG  from STORECGFKM where rtrim(BILLID) = @BILLID)
     set @VENDORID =   (select  VENDOR_client_id  from STORECGFKM where rtrim(BILLID) = @BILLID)
     set @SFKTYPE =   (select  isnull(SFKTYPE,0)  from STORECGFKM where rtrim(BILLID) = @BILLID)
     set @BANKID =   (select  BANKID  from STORECGFKM where rtrim(BILLID) = @BILLID)
     set @VendorFLAG =   (select  ISNULL(VendorFLAG,1)  from STORECGFKM where rtrim(BILLID) = @BILLID)

		IF   @SFKTYPE=0
		begin
			      rollback transaction trans_CGFK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='付款类型不能为空，单据不能记帐'
                                          RETURN
		end

                                      IF NOT (exists (select * from VENDOR where VENDORID=@VENDORID))
                                     BEGIN
			      rollback transaction trans_CGFK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='供应商不能为空或供应商不存在，单据不能记帐'
                                          RETURN
			END
		IF   @SFKTYPE  IN (1,2)    ---@SFKTYPE =3   为不记录
		begin

                             IF NOT (exists (select * from BANK where BANKID=@BANKID))
                              BEGIN
			      rollback transaction trans_CGFK
			      set @flagreturn = 0
                                   SET @RETURNSTRING='银行科目不能为空或银行科目不存在，单据不能记帐'
                                   RETURN
	  		     END
		END


		IF  (@VendorFLAG=0) AND  (@SFKTYPE  IN (2,3))   
		begin

			      rollback transaction trans_CGFK
			      set @flagreturn = 0
                              SET @RETURNSTRING='当供应商为客户核算主体时，付款类型只能选择应付账款，否则单据不能记帐！'
                              RETURN
		END


   	 SELECT @SUMAMT= (SELECT AMT  FROM  STORECGFKM   where rtrim(BILLID) = @BILLID)
   	 SELECT @MianAMT= (SELECT ISNULL(MianAMT,0)  FROM  STORECGFKM   where rtrim(BILLID) = @BILLID)

	IF  @VendorFLAG=1
	BEGIN

            IF   (not exists(select *  from VENDORBILLFLOW  where 
             		                                    (rtrim(VENDORID) = @VENDORID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN
             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,0,Null,
		     @inoutFlag,0  )    
            END      ------IF   END
             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,@SUMAMT,Null,
		     -1,0  )    
	IF   @SFKTYPE  =3    ---@SFKTYPE =3   为不记录
	begin
             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,-@SUMAMT,Null,
		     -1,0  )    

	end



		IF @MianAMT <>0
		Begin

             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode+'免付金额',@VENDORID,
		     0,@MianAMT,Null,
		     -1,0  )    

		END
-------------------------------增加应收帐款  是 INOUTFLAG为1

-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM

	end      ------------IF  @VendorFLAG=1



	IF  @VendorFLAG=0
	BEGIN
	      SET @ClientID=@VendorID
	            IF   (not exists(select *  from CLIENTBILLFLOW  where 
             		                                    (rtrim(CLIENTID) = @CLIENTID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@CLIENTID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END


             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE, CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode, @CLIENTID,
		     0,@SUMAMT,Null,
		     1,0 )    
-------------------------------增加应收帐款  是 INOUTFLAG为1

             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE, CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode+'免付金额', @CLIENTID,
		     0,@MianAMT,Null,
		     1,0 )    
-------------------------------增加应收帐款  是 INOUTFLAG为1


                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM
	END         ----------IF  @VendorFLAG=0












------------------------------以下是解决科目帐的算法
	IF   @SFKTYPE  IN (1,2)    ---@SFKTYPE =3   为不记录
	begin

            IF   (not exists(select *  from BANKBILLFLOW  where 
             		                                    (rtrim(BANKID) = @BANKID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,0,Null,
		     @inoutFlag,0  )    
            END      ------IF   END
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,@SUMAMT,Null,
		     -1,0  )    
                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM
	end

    declare SM_Consign_CGFK Cursor for Select  REBILLID,REBILLTYPE,isnull(AMT,0)   as amt     from STORECGFKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CGFK

    fetch SM_Consign_CGFK into @REBILLID,@REBILLTYPE,@AMT

    while @@fetch_status = 0            ----开始
    begin

--	//  1,7
	    IF  @REBILLTYPE= 1  
	    BEGIN
		UPDATE   STORECGRKM   SET DISCAMT= isnull(DISCAMT,0)+@AMT   WHERE BILLID=@REBILLID 
	    END 
	    IF  @REBILLTYPE= -2
	    BEGIN
		UPDATE   VENDOR  SET SURAMT= isnull(SURAMT,0)+@AMT   WHERE  VENDORID=@REBILLID 

	    END 

	    fetch SM_Consign_CGFK into @REBILLID,@REBILLTYPE,@AMT

    END

    close SM_Consign_CGFK
    deallocate SM_Consign_CGFK



   update  STORECGFKM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CGFK
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CGFK
      set @flagreturn = 0
   end
end








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[STORE_CGFK_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @REBILLID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @BANKID    varchar(15)               --明细存货编号
declare @BATCHCODE   varchar(30)                     --序列号
declare @VENDORID   varchar(30)                     --序列号
declare @INF_COSTINGTYPEID   INT
declare @REBILLTYPE   INT
declare @REFQTY   NUMERIC(20, 8)
declare @AMT  NUMERIC(20, 8)
declare @STOREHSFS   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STORECGFKM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STORECGFKM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CGFK_DEL   --事物开始


	     set @VENDORID =   (select  VENDOR_CLIENT_ID  from STORECGFKM where rtrim(BILLID) = @BILLID)

	     set @BANKID =   (select  BANKID  from STORECGFKM where rtrim(BILLID) = @BILLID)

		DELETE   VENDORBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=8

                            execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM

		DELETE   BANKBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=8

                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM

    declare SM_Consign_CGFK_DEL Cursor for Select  REBILLID,REBILLTYPE, isnull(AMT,0)  as AMT     from STORECGFKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CGFK_DEL

    fetch SM_Consign_CGFK_DEL into @REBILLID,@REBILLTYPE,@AMT

    while @@fetch_status = 0            ----开始
    begin

--	//  1,7
	    IF  @REBILLTYPE= 1  
	    BEGIN
		UPDATE   STORECGRKM   SET DISCAMT= isnull(DISCAMT,0)-@AMT   WHERE BILLID=@REBILLID 
	    END 
	    IF  @REBILLTYPE= -2
	    BEGIN
		UPDATE   VENDOR  SET SURAMT= isnull(SURAMT,0)-@AMT   WHERE  VENDORID=@REBILLID 

	    END 


	    fetch SM_Consign_CGFK_DEL into @REBILLID,@REBILLTYPE,@AMT

    END
    close SM_Consign_CGFK_DEL
    deallocate SM_Consign_CGFK_DEL




   update  STORECGFKM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CGFK_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CGFK_DEL
      set @flagreturn = 0
   end
end






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











CREATE PROCEDURE [dbo].[STORE_CGFP]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---是否现款标志
declare @VENDORFLAG int           ---单据对供应商精确运算标志
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @VENDORID   varchar(15)               --明细存货编号
declare @MakeMan   varchar(15)               --明细存货编号
declare @invoiceCode  varchar(200)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20, 8)                          --数量
declare @SUMAMT NUMERIC(20, 8)                          --单据总金额
declare @REBILLID varchar(15)
declare @REBILLSUMAMT NUMERIC(20,2)                          --引用数量
declare @REBILLDISCAMT NUMERIC(20,2)                          --引用数量
declare @AMT NUMERIC(20,2)                          --引用数量

declare @refqty NUMERIC(20, 8)                          --引用数量
declare @PRICE  NUMERIC(20, 8)               --含税单价
declare @APRICE  NUMERIC(20, 8)               --含税单价
declare @RATE  NUMERIC(20, 8)               --含税单价
declare @BATCHCODE varchar(30)                     --序列号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @UNITID VARCHAR(25)
declare @BILLDATE DATEtime
declare @invoiceDate DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @invoiceFlag  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @PRICEQX   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间


       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

     set @BillDate =   (select BillDate  from STORECGFPM where rtrim(BILLID) = @BILLID)
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     

      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END

if  (select isnull(flagPost,0) from STORECGFPM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CGFP   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STORECGFPM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STORECGFPM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STORECGFPM where rtrim(BILLID) = @BILLID)
     set @MakeMan =   (select MakeMan  from STORECGFPM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STORECGFPM where rtrim(BILLID) = @BILLID)
     set @VENDORID =   (select  VENDOR_CLIENT_ID  from STORECGFPM where rtrim(BILLID) = @BILLID)
     set @invoiceCode =   (select invoiceCode  from STORECGFPM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @invoiceDate =   (select invoiceDate  from STORECGFPM where rtrim(BILLID) = @BILLID)
     set @invoiceFlag =   (select  ISNULL(invoiceFlag,1)  from STORECGFPM where rtrim(BILLID) = @BILLID)


--------------------------------------------------

----REBILLSUMAMT  单据总额
----REBILLDISCAMT  已开票
----AMT   本次开票

    declare SM_Consign_CGFP Cursor for Select  ITEMNO,REBILLID, REBILLSUMAMT,REBILLDISCAMT,ISNULL(AMT,0) as AMT 
                                                                       from STORECGFPD where rtrim(BILLID) = @BILLID AND ISNULL(AMT,0)<>0

    Open SM_Consign_CGFP

    fetch SM_Consign_CGFP into @ITEMNO,@REBILLID, @REBILLSUMAMT,@REBILLDISCAMT,@AMT

    while @@fetch_status = 0            ----开始
    begin


	          UPDATE    STORECGRKM     set    FaPiaoAMT=ISNULL(FaPiaoAMT,0)+@AMT,invoiceCode=ISNULL(invoiceCode,'')+'  '+ISNULL(@invoiceCode,''),
					invoiceDate=@invoiceDate,invoiceFlag=@invoiceFlag
             		           WHERE rtrim(BILLID) = @REBILLID

	  
	          UPDATE    STORECGRKM     set    STATUS=1
             		           WHERE FaPiaoAMT = SumAMT and YaoPiaoFlag=1


--------------------
    fetch SM_Consign_CGFP into @ITEMNO,@REBILLID, @REBILLSUMAMT,@REBILLDISCAMT,@AMT

    END           ------- SM_Consign_CGFP  WHILE

    close SM_Consign_CGFP
    deallocate SM_Consign_CGFP

-----------------------以上是解决仓库记帐问题，以下是应付帐款的问题
-----------------------------
   update  STORECGFPM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CGFP
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CGFP
      set @flagreturn = 0
   end
end









----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG










CREATE PROCEDURE [dbo].[STORE_CGFP_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @invoiceCode varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @BATCHCODE   varchar(30)                     --序列号
declare @VENDORID   varchar(30)                     --序列号
declare @INF_COSTINGTYPEID   INT
declare @VENDORFLAG   INT
declare @AMT NUMERIC(20,2)                          --引用数量
declare @billtype   INT
declare @SFLAG   INT
declare @REFQTY   NUMERIC(20, 8)
declare @STOREHSFS   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @REBILLSUMAMT NUMERIC(20,2)                          --引用数量
declare @REBILLDISCAMT NUMERIC(20,2)                          --引用数量
declare @invoiceDate DATEtime
declare @invoiceFlag  INTEGER
declare @REBILLID varchar(15)
declare @ITEMNO varchar(15)               --明细存货编号

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDate =  (select BILLDate  from STORECGFPM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
       IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STORECGFPM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CGFP_DEL   --事物开始

	SELECT @VENDORID=VENDOR_CLIENT_ID    FROM STORECGFPM  where rtrim(BILLID) = @BILLID 
	     set @BillType =   (select BillType  from STORECGFPM where rtrim(BILLID) = @BILLID)
     set @invoiceCode =   (select invoiceCode  from STORECGFPM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @invoiceDate =   (select invoiceDate  from STORECGFPM where rtrim(BILLID) = @BILLID)
     set @invoiceFlag =   (select  ISNULL(invoiceFlag,1)  from STORECGFPM where rtrim(BILLID) = @BILLID)



    declare SM_Consign_CGFP_DEL Cursor for Select  ITEMNO,REBILLID, REBILLSUMAMT,REBILLDISCAMT,ISNULL(AMT,0) as AMT 
                                                                       from STORECGFPD where rtrim(BILLID) = @BILLID AND ISNULL(AMT,0)<>0

    Open SM_Consign_CGFP_DEL

    fetch SM_Consign_CGFP_DEL into @ITEMNO,@REBILLID, @REBILLSUMAMT,@REBILLDISCAMT,@AMT

    while @@fetch_status = 0            ----开始
    begin
	          UPDATE    STORECGRKM     set    FaPiaoAMT=ISNULL(FaPiaoAMT,0)-@AMT,
			invoiceCode=substring(invoiceCode,1,charindex(@invoiceCode,invoiceCode) -1) + 
			substring(invoiceCode,charindex(@invoiceCode,invoiceCode)+ len(@invoiceCode) ,len(invoiceCode)), 
					invoiceDate=NULL,invoiceFlag=@invoiceFlag
             		           WHERE rtrim(BILLID) = @REBILLID
	  

	          UPDATE    STORECGRKM     set    STATUS=0
             		           WHERE FaPiaoAMT <> SumAMT and YaoPiaoFlag=1
--------------------
    fetch SM_Consign_CGFP_DEL into @ITEMNO,@REBILLID, @REBILLSUMAMT,@REBILLDISCAMT,@AMT

    END           ------- SM_Consign_CGFP_DEL  WHILE

    close SM_Consign_CGFP_DEL
    deallocate SM_Consign_CGFP_DEL

                             DELETE   DetailBillFlow     WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 AND BILLTYPE=@billtype
--------------------------------------以上上全部删除单据  是解决多次记帐失败的问题

   update  STORECGFPM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CGFP_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CGFP_DEL
      set @flagreturn = 0
   end
end









----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG





































--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[STORE_CGRK]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare                   @RETURNSTRING00            varchar(60)       ---单据编号   
declare                   @flagreturn00 int      ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
declare @SFLAG  int                    ---是否现款标志
declare @VendorFLAG  int                    ---是否现款标志
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @VENDORID   varchar(15)               --明细存货编号
declare @YunShuDWID   varchar(15)               --明细存货编号
declare @BuMenID   varchar(15)               --明细存货编号
declare @ClientID   varchar(15)               --明细存货编号
declare @bankID   varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @REDetailBillFlowID varchar(15)               --明细存货编号
declare @GJRKDetailBillFlowID varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @UNITqty NUMERIC(20,10)                          --数量
declare @SUMAMT NUMERIC(20,10)                          --单据总金额
declare @TAXRATE NUMERIC(20,10)                          --单据总金额
declare @RATE NUMERIC(20,10)                          --单据总金额
declare @refqty NUMERIC(20,10)                          --引用数量
declare @KEYONGqty NUMERIC(20,10)                          --引用数量
declare @UNITPRICE NUMERIC(20,10)                          --引用数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @YunFeiFT  NUMERIC(20,10)               --含税单价
declare @BILLTYPE INTEGER
declare @PRICETYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLCODE00 VARCHAR(25)
declare @BILLID00 VARCHAR(25)
declare @ITEMNO00 VARCHAR(25)
declare @MAKEMAN VARCHAR(25)
declare @ChaCheSID VARCHAR(25)
declare @PanYunSID VARCHAR(25)
declare @REITEMNO varchar(15)               --明细存货编号
declare @KEYONGunitQTY  NUMERIC(20,10)               --含税单价
declare @KEYONGquantity  NUMERIC(20,10)               --含税单价
declare @TMPunitQTY  NUMERIC(20,10)               --含税单价
declare @TMPquantity  NUMERIC(20,10)               --含税单价

declare @YunFeiZhiFuFX VARCHAR(25)  ----运费支付方向
declare @ChaChePrice  NUMERIC(20,10)               --含税单价
declare @PanYunPrice  NUMERIC(20,10)               --含税单价
declare @ChaCheSYunfei  NUMERIC(20,10)               --含税单价
declare @PanYunSYunfei  NUMERIC(20,10)               --含税单价
declare @QiTaFeiYong  NUMERIC(20,10)               --含税单价
declare @YunFeiSum  NUMERIC(20,10)               --含税单价
declare @KEYONGSTOREID  VARCHAR(25)
declare @REGJRKITEMNO VARCHAR(25)
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @JianShu [int] 
declare @MeiJianQty [T_QUANTITY] 
declare @LingTou [T_QUANTITY] 

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

     set @BillDate =   (select BillDate  from STORECGRKM where rtrim(BILLID) = @BILLID)
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     

    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END

if  (select isnull(flagPost,0) from STORECGRKM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CGRK   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STORECGRKM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STORECGRKM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STORECGRKM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STORECGRKM where rtrim(BILLID) = @BILLID)
     set @BuMenID =   (select BuMenID  from  STORECGRKM where rtrim(BILLID) = @BILLID)   ---------收款银行
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STORECGRKM where rtrim(BILLID) = @BILLID)
     set @VendorFLAG =   (select  ISNULL(VendorFLAG,1)  from STORECGRKM where rtrim(BILLID) = @BILLID)
     set @VENDORID =   (select  VENDORID  from STORECGRKM where rtrim(BILLID) = @BILLID)
     set @BANKID =   (select BANKID  from STORECGRKM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @ChaCheSID =   (select ChaCheSID  from STORECGRKM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @PanYunSID =   (select PanYunSID  from STORECGRKM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @YunFeiZhiFuFX =   (select YunFeiZhiFuFX  from STORECGRKM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @ChaChePrice =   (select ISNULL(ChaChePrice,0)  from STORECGRKM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @PanYunPrice =   (select ISNULL(PanYunPrice,0)  from STORECGRKM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @ChaCheSYunFei=    (select ROUND(ISNULL(ChaChePrice,0)*SumQUANTITY,2) from STORECGRKM where rtrim(BILLID) = @BILLID)   ---------付款银行 
     set @PanYunSYunFei=    (select ROUND(ISNULL(PanYunPrice,0)*SumQUANTITY,2) from STORECGRKM where rtrim(BILLID) = @BILLID)   ---------付款银行 
     set @YunFeiSum=   @ChaCheSYunFei+@PanYunSYunFei
     set @QiTaFeiYong =   (select ISNULL(QiTaFeiYong,0)  from STORECGRKM where rtrim(BILLID) = @BILLID)   ---------付款银行

/*declare @ChaCheSID VARCHAR(25)
declare @PanYunSID VARCHAR(25)
declare @YunFeiZhiFuFX VARCHAR(25)  ----运费支付方向
declare @ChaChePrice  NUMERIC(20,10)               --含税单价
declare @PanYunPrice  NUMERIC(20,10)               --含税单价  */

                                
                              IF (NOT exists(select * from YunShuDW where YunShuDWID=@ChaCheSID)) and @ChaChePrice<>0
                              BEGIN
			      rollback transaction trans_CGRK
			      set @flagreturn = 0
                                      SET @RETURNSTRING='叉车商不能为空或叉车商不存在，单据不能记帐'
                                       RETURN
			END

                              IF (NOT exists(select * from YunShuDW where YunShuDWID=@PanYunSID)) and @PanYunPrice<>0
                              BEGIN
			      rollback transaction trans_CGRK
			      set @flagreturn = 0
                                      SET @RETURNSTRING='盘运商不能为空或盘运商不存在，单据不能记帐'
                                       RETURN
			END


                                      IF NOT (exists (select * from VIEWVENDOR where VENDORID=@VENDORID  and VendorFLAG=@VendorFLAG))
                                     BEGIN
			      rollback transaction trans_CGRK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='供应商不能为空或供应商不存在，单据不能记帐'
                                          RETURN
			END



                       IF @SFLAG=1 and @VendorFLAG=0
                       BEGIN
			      rollback transaction trans_CGRK
			      set @flagreturn = 0
                              SET @RETURNSTRING='当供应商为客户的时候，不允许选择现款采购，单据不能记帐'
                              RETURN
		       END



   	 SELECT @SUMAMT=0


    declare SM_Consign_CGRK Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(UNITPRICE,0)*ISNULL(DISC,0)*0.01 as PRICE, 
                                                                   DetailBillFlowID,ISNULL(UNITQTY,0)  as UNITQTY,REGJRKITEMNO,PRICETYPE,TAXRATE,ISNULL(YunFeiFT,0) as YunFeiFT,JianShu,MeiJianQty,LingTou,REITEMNO    from STORECGRKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CGRK

    fetch SM_Consign_CGRK into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE, @DetailBillFlowID,@UNITQTY,@REGJRKITEMNO,@PRICETYPE,@TAXRATE,@YunFeiFT,@JianShu,@MeiJianQty,@LingTou,@REITEMNO

    while @@fetch_status = 0            ----开始
    begin

-------缺少检测仓库  明日解决

                     set @MeiJianQty =   (select ISNULL(RATE1,0)  from GOODS where  GOODSID = @GOODSID)


                            IF (ISNULL(@JianShu,0)*ISNULL(@MeiJianQty,0)+ISNULL(@LingTou,0)<>@Unitqty) AND (ISNULL(@JianShu,0)<>0 OR ISNULL(@LingTou,0)<>0)
                           BEGIN
	  	      rollback transaction trans_CGRK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='件数*每件数量+零头与数量不等，单据不能记帐'
			    close SM_Consign_CGRK
			    deallocate SM_Consign_CGRK
                                          RETURN
			END

                                      IF NOT (exists (select * from STORE where STOREID=@STOREID))
                                     BEGIN
			      rollback transaction trans_CGRK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库不能为空或仓库不存在，单据不能记帐'
			    close SM_Consign_CGRK
			    deallocate SM_Consign_CGRK
                                          RETURN
			END




                                      IF exists (select * from STORE where STOREID=@STOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_CGRK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_CGRK
			    deallocate SM_Consign_CGRK
                                          RETURN
			END



            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)*0.001  from GOODS where  GOODSID = @GOODSID)

----------------订单处理引用begin

	IF @REITEMNO IS NOT NULL
    BEGIN
	         SELECT   @KEYONGunitQTY = UNITQTY-ISNULL(WCunitQTY,0)   FROM   STORECGDDD    WHERE  ITEMNO=@REITEMNO
	         SELECT   @KEYONGquantity = quantity-ISNULL(WCquantity,0)   FROM   STORECGDDD    WHERE  ITEMNO=@REITEMNO
        IF @KEYONGunitQTY >0  or @KEYONGquantity>0
		BEGIN
		   UPDATE   STORECGDDD   SET WCunitQTY=ISNULL(WCunitQTY,0)+ISNULL(@UNITQTY,0)  WHERE  ITEMNO=@REITEMNO
		   UPDATE   STORECGDDD   SET WCquantity=ISNULL(WCquantity,0)+ISNULL(@qty,0)  WHERE  ITEMNO=@REITEMNO
		   
			SELECT @TMPunitQTY=SUM(UNITQTY-isnull(WCunitQTY,0))  FROM STORECGDDD   WHERE  BILLID IN (SELECT BILLID FROM   STORECGDDD WHERE  ITEMNO=@REITEMNO)
			SELECT @TMPquantity=SUM(quantity-isnull(WCquantity,0))  FROM STORECGDDD   WHERE  BILLID IN (SELECT BILLID FROM   STORECGDDD WHERE  ITEMNO=@REITEMNO)
			IF @TMPunitQTY<=0  OR @TMPquantity <= 0
			BEGIN
			   UPDATE   STORECGDDM   SET STATUS=1  WHERE  BILLID IN (SELECT BILLID FROM   STORECGDDD WHERE  ITEMNO=@REITEMNO)
			END
		END
		ELSE
		BEGIN
			    set @flagreturn = 0
                SET @RETURNSTRING='引用的订单已经完成或终止，请重新修改单据'
			    close  SM_Consign_CGRK
			    deallocate  SM_Consign_CGRK
			    rollback transaction trans_CGRK
                RETURN
		END
	END

----------------订单处理引用end



---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	

	IF @PRICETYPE=1   
	BEGIN
   	 SELECT @SUMAMT=@SUMAMT+ROUND(@price*@QTY*(1+ISNULL(@TAXRATE,0)*0.01),2)
	END
	IF @PRICETYPE=0  
	BEGIN
   	 SELECT @SUMAMT=@SUMAMT+ROUND(@price*@UNITQTY*(1+ISNULL(@TAXRATE,0)*0.01),2)

		IF   @QTY<>0
		BEGIN
		SET  @PRICE=(@UNITQTY*@PRICE)/@QTY
		END

	END



-----------
	IF  @QTY<>0
	begin	
	set @PRICE=(@QTY*@PRICE+@YunFeiFT)/@QTY     -----增加运费分摊
	end
---------------
	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE  ,@DetailBillFlowID, @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT )
	    Values
---	    (@NEWID,@YYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	    (@NEWID,@BillYYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     isnull(@REFQTY,0),0)    
	          UPDATE   STORECGRKD  set    DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_CGRK


-----------====================2012-09-04 begin

	IF   @INF_COSTINGTYPEID=6 
	Begin

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT )
	    Values
---	    (@NEWID,@YYYYMM,2,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	    (@NEWID,@BILLYYYYMM,2,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     isnull(@REFQTY,0),0)    

	END

--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

--------------------
    fetch SM_Consign_CGRK into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE, @DetailBillFlowID,@UNITQTY,@REGJRKITEMNO,@PRICETYPE,@TAXRATE,@YunFeiFT,@JianShu,@MeiJianQty,@LingTou,@REITEMNO

    END           ------- SM_Consign_CGRK  WHILE

    close SM_Consign_CGRK
    deallocate SM_Consign_CGRK

----------------------------可能不需要下面的这几句代码
--------------------------------关键是生成一张新的冲回估价入库单其实很简单
--		  取得新的单据号，用insert  into 就可以完成关键是单据号
--------

                        IF exists (select * from STORECGRKD  where rtrim(BILLID) = @BILLID  AND  REGJRKITEMNO  IN (SELECT ITEMNO FROM STOREGJRKD ))
                        BEGIN
	             		    execute  GET_BILL_NO     'STOREGJRKM',@BILLDATE,'GR',@bill_no_selfd = @BILLCODE00 output
             			    execute  GETKEYVALUE     'STOREGJRKM',@R_KeyValue = @BILLID00 output

             	             			 INSERT  INTO STOREGJRKM   (BILLID,YYYYMM,CODE,MAKEMAN,BILLDATE,STATUS,MEMO,REFERBILLCODE,VENDORID)
		                                      VALUES (@BILLID00,@YYYYMM,@BILLCODE00,@MAKEMAN,@BILLDATE,1,@BILLCODE+'生成',@billid,@VENDORID)
----------------------------------------------------------------------以下是插入从表
		    declare SM_Consign_DATANEXT Cursor for Select  ITEMNO,GOODSID,STOREID,
                                                                   DetailBillFlowID,UNITQTY,QUANTITY,REGJRKITEMNO    from STORECGRKD   where rtrim(BILLID) = @BILLID   AND  REGJRKITEMNO  IN (SELECT ITEMNO   FROM STOREGJRKD )

		    Open   SM_Consign_DATANEXT

		    fetch  SM_Consign_DATANEXT into @ITEMNO,@GOODSID,@STOREID, @DetailBillFlowID,@UNITQTY,@QTY,@REGJRKITEMNO

		    while @@fetch_status = 0            ----开始
		    begin

             		    execute  GETKEYVALUE     'STOREGJRKD',@R_KeyValue = @ITEMNO00 output
			SELECT @UNITPRICE = UNITPRICE,@REDetailBillFlowID=@DetailBillFlowID  FROM STOREGJRKD  WHERE ITEMNO=@REGJRKITEMNO
		    insert into STOREGJRKD 
		    (BILLID, ITEMNO,UNITPRICE,STOREID,GOODSID,UNITQTY,QUANTITY,REDetailBillFlowID)
		    Values
		    (@BILLID00,@ITEMNO00 ,@UNITPRICE,@STOREID,@GOODSID ,-@UNITQTY,-@QTY,@REDetailBillFlowID )    

		    fetch  SM_Consign_DATANEXT into @ITEMNO,@GOODSID,@STOREID, @DetailBillFlowID,@UNITQTY,@QTY,@REGJRKITEMNO

		    END           ------- SM_Consign_DATANEXT  WHILE

		    close SM_Consign_DATANEXT
		    deallocate SM_Consign_DATANEXT


	                 execute  STORE_TALLY  @BILLID00 ,'STOREGJRKM',@RETURNSTRING00  OUTPUT,  @flagreturn00    output
             		    IF  @flagreturn00<>2
	                 BEGIN
		      rollback transaction trans_CGRK
		      set @flagreturn = 0
             		    RETURN
		    END
     END
-----------------------以上是解决仓库记帐问题，以下是应付帐款的问题

        set @SUMAMT=@SUMAMT+@QiTaFeiYong


        IF @YunFeiZhiFuFX='厂方垫付运费' 
        begin
        set @SUMAMT=@SUMAMT+@YunFeiSum
        end


        IF @YunFeiZhiFuFX='我方支付运费' 
        begin

                    IF  @ChaChePrice<>0
		    begin
			set @YunShuDWID=@ChaCheSID
	            IF   (not exists(select *  from YunShuDWBILLFLOW  where 
             		                                    (rtrim(YunShuDWID) = @YunShuDWID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@YunShuDWID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
	             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@YunShuDWID,
		     0,@ChaCheSYunFei,Null,
		     1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      YunShuDW_CACULATOR_YYYYMM   @YunShuDWID,@YYYYMM

		    end

                    IF  @PanYunPrice<>0
		    begin
			set @YunShuDWID=@PanYunSID


	            IF   (not exists(select *  from YunShuDWBILLFLOW  where 
             		                                    (rtrim(YunShuDWID) = @YunShuDWID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@YunShuDWID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
	             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@YunShuDWID,
		     0,@PanYunSYunFei,Null,
		     1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      YunShuDW_CACULATOR_YYYYMM   @YunShuDWID,@YYYYMM

		        end
        end   ------我方支付运费的情况
--------------------------------------------

	IF @SFLAG=0  and  @VendorFLAG=1
	BEGIN
	            IF   (not exists(select *  from VENDORBILLFLOW  where 
             		                                    (rtrim(VENDORID) = @VENDORID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
	             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,@SUMAMT,Null,
		     1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM

	END     ----------------     IF @SFLAG=0


	IF @SFLAG=0  and  @VendorFLAG=0
	BEGIN
	      SET @ClientID=@VendorID
	            IF   (not exists(select *  from CLIENTBILLFLOW  where 
             		                                    (rtrim(CLIENTID) = @CLIENTID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE, CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT  )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode, @CLIENTID,
		     0,0,Null,
		     @inoutFlag,0 )    
	            END      ------IF   END
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE, CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT,BuMenID   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode, @CLIENTID,
		     0,-@SUMAMT,Null,
		     1,0 ,@BuMenID )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM
	END         ---------------IF @SFLAG=0





------------------------------------2004-07-05--------------解决采购付款问题

	IF @SFLAG=1  AND  NOT( @BANKID='APSOFT')
	BEGIN
                                      IF NOT (exists (select * from BANK where BANKID=@BANKID))
                                     BEGIN
			      rollback transaction trans_CGRK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='银行科目不能为空或银行科目不存在，单据不能记帐'
                                          RETURN
			END


------------------------------以下是解决科目帐的算法

	            IF   (not exists(select *  from BANKBILLFLOW  where 
             		                                    (rtrim(BANKID) = @BANKID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
	             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
			    insert into BANKBILLFLOW 
			    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
			     BAMOUNT,INAMOUNT,OUTAMOUNT,
			     INOUTFLAG,EAMOUNT   )
			    Values
			    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
			     0,0,Null,
			     @inoutFlag,0  )    
	            END      ------IF   END
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,@SUMAMT,Null,
		     -1,0  )    
	                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM

         update  STORECGRKM  set DISCAMT=VendorHKSum       where ltrim(rtrim(BILLID)) = @BILLID 

	END  ---------------	IF @SFLAG=1
--------更新定价-------begin--------------
Insert into  CGRKGoodsPrice ([ID]      ,[BILLID]      ,[ITEMNO]   ,[STOREID]
      ,[GOODSID]      ,[PRICE]      ,[QUANTITY]      ,[MEMO]
      ,[TAXRATE]      ,[DISC]      ,[UNITPRICE]      ,[UNITQTY]
      ,[PRICETYPE]      ,[AMT]      ,[TAXAMT]      ,[YunFeiFT]
      ,[CaiZhi]      ,[ChanDi]      ,[AMOUNT]      ,[invoiceqty]
      ,[invoiceamt]      ,[InvoiceNow]      ,[SPECNameD]      ,[JianShu]
      ,[MeiJianQty]      ,[LingTou]      ,[FuZhuQTY]      ,[ZongLen])

 select BILLID+ITEMNO as  ID      ,[BILLID]      ,[ITEMNO]   ,[STOREID]
      ,[GOODSID]      ,[PRICE]      ,[QUANTITY]      ,[MEMO]
      ,[TAXRATE]      ,[DISC]      ,[UNITPRICE]      ,[UNITQTY]
      ,[PRICETYPE]      ,[AMT]      ,[TAXAMT]      ,[YunFeiFT]
      ,[CaiZhi]      ,[ChanDi]      ,[AMOUNT]      ,[invoiceqty]
      ,[invoiceamt]      ,[InvoiceNow]      ,[SPECNameD]      ,[JianShu]
      ,[MeiJianQty]      ,[LingTou]      ,[FuZhuQTY]      ,[ZongLen]
      from storecgrkd where BILLID=@BILLID
      
 update   CGRKGoodsPrice set CGRKGoodsPrice.VENDORID=storecgrkM.VENDORID,
 CGRKGoodsPrice.EMPID=storecgrkM.EMPID,
 CGRKGoodsPrice.BILLDATE=storecgrkM.BILLDATE,
 CGRKGoodsPrice.CODE=storecgrkM.CODE   from storecgrkM,CGRKGoodsPrice 
 where CGRKGoodsPrice.BILLID=storecgrkM.BILLID   and storecgrkM.BILLID=@BILLID
 --------更新理算系数---只有数量或者只有重量
 update   CGRKGoodsPrice set CGRKGoodsPrice.LSRate=Goods.Rate
   from GOODS,CGRKGoodsPrice 
 where CGRKGoodsPrice.GOODSID=GOODS.GOODSID   and CGRKGoodsPrice.BILLID=@BILLID
 AND (ISNULL(CGRKGoodsPrice.unitqty,0)=0 OR ISNULL(CGRKGoodsPrice.quantity,0)=0 )
 
  update   CGRKGoodsPrice set LSRate=quantity/unitqty
   from CGRKGoodsPrice  where  BILLID=@BILLID  and ISNULL(quantity,0)<>0 and ISNULL(unitqty,0)<>0

 update   CGRKGoodsPrice set unitqty=quantity/LSRate
   from CGRKGoodsPrice  where  BILLID=@BILLID  and ISNULL(unitqty,0)=0 and LSRate<>0
 
 update   CGRKGoodsPrice set quantity=unitqty*isnull(LSRate,0)
   from CGRKGoodsPrice  where  BILLID=@BILLID  and ISNULL(quantity,0)=0 

   update  CGRKGoodsPrice  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2) where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  CGRKGoodsPrice  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)   where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0

   update  CGRKGoodsPrice  set   CGDSPrice  =  unitprice where ltrim(rtrim(BILLID)) = @BILLID      AND PRICETYPE=1
   update  CGRKGoodsPrice  set   CGDSPrice  =  AMT/quantity where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0  and ISNULL(quantity,0)<>0
   
   update  CGRKGoodsPrice  set   CGMSPrice  =  unitprice where ltrim(rtrim(BILLID)) = @BILLID      AND PRICETYPE=0
   update  CGRKGoodsPrice  set   CGMSPrice  =  AMT/unitqty where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1  and ISNULL(unitqty,0)<>0
   update  CGRKGoodsPrice  set   DEQTY  =  quantity,MEQTY=unitqty 
 





--------更新定价-------end--------------



-----------------------------
   update  STORECGRKM  set  flagPost = 1,YYYYMM =@BILLYYYYMM ,SUMAMT=VendorHKSum ,INVOICEAMT=0           where ltrim(rtrim(BILLID)) = @BILLID 
     
   update  STORECGRKD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)          where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STORECGRKD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)   where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CGRK
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CGRK
      set @flagreturn = 0
   end
end



















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG
















----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[STORE_CGRK_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare   @flagreturn00   int  ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @GJRKDetailBillFlowID  varchar(15)               --明细存货编号
declare @VENDORID   varchar(30)                     --序列号
declare @ClientID   varchar(30)                     --序列号
declare @VendorFLAG  int                    ---是否现款标志
declare @BILLIDGJRK   varchar(30)                     --序列号
declare @REITEMNO   varchar(30)                     --序列号
declare @INF_COSTINGTYPEID   INT
declare @billtype   INT
declare @SFLAG   INT
declare @REFQTY   NUMERIC(20,10)
declare @quantity   NUMERIC(20,10)
declare @unitqty   NUMERIC(20,10)
declare @ChaCheSID VARCHAR(25)
declare @PanYunSID VARCHAR(25)
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BillDate =   (select BillDate  from STORECGRKM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STORECGRKM where ltrim(rtrim(BILLID)) = @BILLID ) = 0 
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CGRK_DEL   --事物开始

	SELECT @VENDORID=VENDORID    FROM STORECGRKM  where rtrim(BILLID) = @BILLID 
     set @BillType =   (select BillType  from STORECGRKM where rtrim(BILLID) = @BILLID)
     set @VendorFLAG =   (select  ISNULL(VendorFLAG,1)  from STORECGRKM where rtrim(BILLID) = @BILLID)


			   IF exists (select * from STORECGFKD  where REBILLID= @BILLID  and rebilltype=1   )
			BEGIN
                                              SET @RETURNSTRING=' 此单据已经被采购付款单引用不能取消记帐！  '
			      rollback transaction trans_CGRK_DEL
			      set @flagreturn = 0
                                         RETURN
			END

			   IF exists (select * from STORECGFPD  where REBILLID= @BILLID     )
			BEGIN
                                              SET @RETURNSTRING=' 此单据已经被采购发票引用不能取消记帐！  '
			      rollback transaction trans_CGRK_DEL
			      set @flagreturn = 0
                                         RETURN
			END


    declare SM_Consign_CGRK_DEL Cursor for Select GOODSID,DetailBillFlowID,STOREID,BILLID,quantity ,REITEMNO,UNITQTY   from STORECGRKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CGRK_DEL

    fetch SM_Consign_CGRK_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@BILLID,@quantity,@REITEMNO,@UNITQTY

    while @@fetch_status = 0            ----开始
    begin
	            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)

----------------订单处理引用begin

	IF @REITEMNO IS NOT NULL
    BEGIN
		   UPDATE   STORECGDDD   SET WCunitQTY=ISNULL(WCunitQTY,0)-ISNULL(@UNITQTY,0)  WHERE  ITEMNO=@REITEMNO
		   UPDATE   STORECGDDD   SET WCquantity=ISNULL(WCquantity,0)-ISNULL(@QUANTITY,0)  WHERE  ITEMNO=@REITEMNO
  		   UPDATE   STORECGDDM   SET STATUS=0  WHERE  BILLID IN (SELECT BILLID FROM   STORECGDDD WHERE  ITEMNO=@REITEMNO)
	END

----------------订单处理引用end
                             DELETE   DetailBillFlow     WHERE  ID=@DetailBillFlowID
--------------------------------------以上是删除一条单据明细
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@STOREID AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
-------------------
    fetch SM_Consign_CGRK_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@BILLID,@quantity,@REITEMNO,@UNITQTY

    END           ------- SM_Consign_CGRK_DEL  WHILE

    close SM_Consign_CGRK_DEL
    deallocate SM_Consign_CGRK_DEL

                             DELETE   DetailBillFlow     WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND (YYYYMMBILL in (1,2)) AND BILLTYPE=@billtype
--------------------------------------以上上全部删除单据  是解决多次记帐失败的问题

----------------------------
	     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STORECGRKM where rtrim(BILLID) = @BILLID)
	     set @BANKID =   (select BANKID  from STORECGRKM where rtrim(BILLID) = @BILLID)   ---------付款银行


     set @ChaCheSID =   (select ChaCheSID  from STORECGRKM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @PanYunSID =   (select PanYunSID  from STORECGRKM where rtrim(BILLID) = @BILLID)   ---------付款银行


		DELETE   YunShuDWBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@BILLTYPE
    		         execute      YunShuDW_CACULATOR_YYYYMM   @ChaCheSID,@YYYYMM
    		         execute      YunShuDW_CACULATOR_YYYYMM   @PanYunSID,@YYYYMM


		SELECT @VENDORID =(SELECT VENDORID FROM STORECGRKM     where ltrim(rtrim(BILLID)) = @BILLID )
		
		IF @SFLAG=0   and  @VendorFLAG=1
		BEGIN
			DELETE   VENDORBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@BILLTYPE
             		               execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM
	                             DELETE  VENDORBILLFLOW    WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 AND BILLTYPE=@billtype
--------------------------------------以上上全部删除单据  是解决多次记帐失败的问题

		END     
		IF @SFLAG=0   and  @VendorFLAG=0
		BEGIN
		      SET @ClientID=@VendorID
	
				DELETE   CLIENTBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@billTYPE
                	            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM
	                             DELETE  CLIENTBILLFLOW   WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 AND BILLTYPE=@billtype
--------------------------------------以上上全部删除单据  是解决多次记帐失败的问题

		END     

		IF @SFLAG=1
		BEGIN
			DELETE BANKBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@BILLTYPE
	                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM
	                             DELETE  BANKBILLFLOW    WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 AND BILLTYPE=@billtype
		END
-----------------------------------------------
			
         DELETE  CGRKGoodsPrice    WHERE  ltrim(rtrim(BILLID)) = @BILLID 			

   update  STORECGRKM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CGRK_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CGRK_DEL
      set @flagreturn = 0
   end
end

----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG






















--------------------------------------------------------------------

CREATE PROCEDURE [STORE_CGTH]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @VENDORID   varchar(15)               --明细存货编号
declare @clientID   varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @bankid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @UNITqty NUMERIC(20,10)                          --数量
declare @SUMAMT NUMERIC(20,10)                          --数量
declare @STOREIDEQTY   NUMERIC(20,10)                          --数量
declare @RATE   NUMERIC(20,10)                          --数量
declare @refqty NUMERIC(20,10)                          --数量
declare @TAXRATE NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID varchar(30)                     --序列号
declare @GOODSNAME varchar(30)                     --序列号
declare @BILLTYPE INTEGER
declare @PRICETYPE INTEGER
declare @count INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @B_CODE VARCHAR(25)
declare @yyyymm_flag INTEGER
declare @STOREHSFS   INTEGER
declare @NEGCLOSEOFF   bit
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @JianShu [int] 
declare @MeiJianQty [T_QUANTITY] 
declare @LingTou [T_QUANTITY] 
       SELECT    @NEGCLOSEOFF=(SELECT  NEGCLOSEOFF  FROM   ACCINFO    WHERE   GUID='0001' )           


       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @BillDate =   (select BillDate  from STORECGTHM where rtrim(BILLID) = @BILLID)

      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END



if  (select isnull(flagPost,0) from STORECGTHM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CGTH   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STORECGTHM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STORECGTHM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STORECGTHM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STORECGTHM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select   ISNULL(SFLAG,0)   from STORECGTHM where rtrim(BILLID) = @BILLID)
     set @VENDORID =   (select  VENDORID  from STORECGTHM where rtrim(BILLID) = @BILLID)
     set @CLIENTID =   (select CLIENTID  from STORECGTHM where rtrim(BILLID) = @BILLID)    ----------收付款方式
     set @BANKID =   (select BANKID  from STORECGTHM where rtrim(BILLID) = @BILLID)   ---------付款银行


                                      IF NOT (exists (select * from VENDOR where VENDORID=@VENDORID))
                                     BEGIN
			      rollback transaction trans_CGTH
			      set @flagreturn = 0
                                              SET @RETURNSTRING='供应商不能为空或供应商不存在，单据不能记帐'
                                          RETURN
			END
   	 SELECT @SUMAMT=0


    declare SM_Consign_CGTH Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(UNITPRICE,0)*ISNULL(DISC,0)*0.01 as PRICE, 
                                                                   DetailBillFlowID,REDetailBillFlowID,ISNULL(UNITQTY,0)  as UNITQTY,PRICETYPE,TAXRATE,JianShu,MeiJianQty,LingTou    from STORECGTHD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CGTH

    fetch SM_Consign_CGTH into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE, @DetailBillFlowID,@REDetailBillFlowID,@UNITQTY,@PRICETYPE,@TAXRATE,@JianShu,@MeiJianQty,@LingTou

    while @@fetch_status = 0            ----开始
    begin

                     set @MeiJianQty =   (select ISNULL(RATE1,0)  from GOODS where  GOODSID = @GOODSID)


                            IF (ISNULL(@JianShu,0)*ISNULL(@MeiJianQty,0)+ISNULL(@LingTou,0)<>@Unitqty) AND (ISNULL(@JianShu,0)<>0 OR ISNULL(@LingTou,0)<>0)
                                     BEGIN
			      rollback transaction trans_CGTH
			      set @flagreturn = 0
                                              SET @RETURNSTRING='件数*每件数量+零头与数量不等，单据不能记帐'
			    close SM_Consign_CGTH
			    deallocate SM_Consign_CGTH
                                          RETURN
			END

            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)*0.001  from GOODS where  GOODSID = @GOODSID)

---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	

	IF @PRICETYPE=1   
	BEGIN
   	 SELECT @SUMAMT=@SUMAMT+ROUND(@price*@QTY*(1+ISNULL(@TAXRATE,0)*0.01),2)
	END
	IF @PRICETYPE=0  
	BEGIN
   	 SELECT @SUMAMT=@SUMAMT+ROUND(@price*@UNITQTY*(1+ISNULL(@TAXRATE,0)*0.01),2)
		IF   @QTY<>0
		BEGIN
		SET  @PRICE=(@UNITQTY*@PRICE)/@QTY
		END


	END

		SELECT @QTY=0-@QTY


                                      IF NOT (exists (select * from STORE where STOREID=@STOREID))
                                     BEGIN
			      rollback transaction trans_CGTH
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close SM_Consign_CGTH
			    deallocate SM_Consign_CGTH
                                          RETURN
			END




                                      IF exists (select * from STORE where STOREID=@STOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_CGTH
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_CGTH
			    deallocate SM_Consign_CGTH
                                          RETURN
			END



                                IF    @NEGCLOSEOFF=0 
			BEGIN 
	                             	 EXEC   GETGOODSIDEQTY  @STOREID,@GOODSID,@YYYYMM,@EQTY=@STOREIDEQTY   OUTPUT
	                                        IF  - @QTY >  ISNULL(@STOREIDEQTY,0)
             		                        BEGIN
                          		                  SET  @GOODSNAME =(SELECT NAME  FROM GOODS WHERE GOODSID=@GOODSID)
				      rollback transaction trans_CGTH
				      set @flagreturn = 0
             		                                 SET @RETURNSTRING='此'+@GOODSNAME+'库存不足不能记帐'
				    close SM_Consign_CGTH
				    deallocate SM_Consign_CGTH
	                                          RETURN
				END
			END 

            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)

	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE  ,@DetailBillFlowID, @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	    REFQTY,REFCOUNT  )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@itemNo,@GoodsID,
	     -@QTY,@price,Null,Null,@INF_COSTINGTYPEID,@UNITQTY,
	     @QTY,@price,@StoreID,'F',-1,@QTY*@PRICE,null,
	     isnull(@REFQTY,0),0 )    
	          UPDATE   STORECGTHD  set    DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_CGTH

--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

----------------------------------------
    fetch SM_Consign_CGTH into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@DetailBillFlowID,@REDetailBillFlowID,@UNITQTY,@PRICETYPE,@TAXRATE,@JianShu,@MeiJianQty,@LingTou

    END           ------- SM_Consign_CGTH  WHILE

    close SM_Consign_CGTH
    deallocate SM_Consign_CGTH

-------------------------
   	 SELECT @SUMAMT=0-@SUMAMT


-----------------------以上是解决仓库记帐问题，以下是应付帐款的问题
	IF @SFLAG=0
	BEGIN
	            IF   (not exists(select *  from VENDORBILLFLOW  where 
             		                                    (rtrim(VENDORID) = @VENDORID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
	             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,@SUMAMT,Null,
		    1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM

	END     ----------------     IF @SFLAG=0

------------------------------------2004-07-05--------------解决采购付款问题

	IF @SFLAG=1  AND  NOT( @BANKID='APSOFT')
	BEGIN
                                      IF NOT (exists (select * from BANK where BANKID=@BANKID))
                                     BEGIN
			      rollback transaction trans_CGTH
			      set @flagreturn = 0
                                              SET @RETURNSTRING='银行科目不能为空或银行科目不存在，单据不能记帐'
                                          RETURN
			END


------------------------------以下是解决科目帐的算法

	            IF   (not exists(select *  from BANKBILLFLOW  where 
             		                                    (rtrim(BANKID) = @BANKID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
	             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
			    insert into BANKBILLFLOW 
			    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
			     BAMOUNT,INAMOUNT,OUTAMOUNT,
			     INOUTFLAG,EAMOUNT   )
			    Values
			    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
			     0,0,Null,
			     @inoutFlag,0  )    
	            END      ------IF   END
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,-@SUMAMT,Null,
		     1,0  )    
	                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM

	END  ---------------	IF @SFLAG=1
-----------------------------


   update  STORECGTHM  set  flagPost = 1,YYYYMM =@BILLYYYYMM , SUMAMT= @SUMAMT ,VendorHKSum=@SUMAMT,INVOICEAMT=0         where ltrim(rtrim(BILLID)) = @BILLID 
     
   update  STORECGTHD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)          where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STORECGTHD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)   where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CGTH
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CGTH
      set @flagreturn = 0
   end
end






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG















----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_CGTH_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @REDetailBillFlowID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @BANKID   varchar(30)                     --序列号
declare @VENDORID   varchar(30)                     --序列号
declare @INF_COSTINGTYPEID   INT
declare @REFQTY   NUMERIC(20,10)
declare @QUANTITY   NUMERIC(20,10)
declare @SFLAG   INTEGER
declare @billTYPE   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间


       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BillDate =   (select BillDate  from STORECGTHM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STORECGTHM where ltrim(rtrim(BILLID)) = @BILLID ) = 0 
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CGTH_DEL   --事物开始

	SELECT @VENDORID=VENDORID    FROM STORECGTHM  where rtrim(BILLID) = @BILLID 
	SELECT @BILLTYPE=BILLTYPE    FROM STORECGTHM  where rtrim(BILLID) = @BILLID 

    declare SM_Consign_CGTH_DEL Cursor for Select GOODSID,DetailBillFlowID,STOREID,QUANTITY,REDetailBillFlowID    from STORECGTHD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CGTH_DEL

    fetch SM_Consign_CGTH_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@QUANTITY,@REDetailBillFlowID

    while @@fetch_status = 0            ----开始
    begin
                             DELETE   DetailBillFlow   WHERE  ID=@DetailBillFlowID
       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID

                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@STOREID AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
--------------------
	    fetch SM_Consign_CGTH_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@QUANTITY,@REDetailBillFlowID

    END           ------- SM_Consign_CGTH_DEL  WHILE

    close SM_Consign_CGTH_DEL
    deallocate SM_Consign_CGTH_DEL


----------------------------
                             DELETE   DetailBillFlow     WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 AND BILLTYPE=@BILLTYPE

	     set @SFLAG =   (select  ISNULL(SFLAG,0)  from  STORECGTHM where rtrim(BILLID) = @BILLID)
	     set @BANKID =   (select BANKID  from  STORECGTHM where rtrim(BILLID) = @BILLID)   ---------付款银行

		SELECT @VENDORID =(SELECT VENDORID FROM STORECGTHM    where ltrim(rtrim(BILLID)) = @BILLID )
		
		IF @SFLAG=0
		BEGIN
			DELETE   VENDORBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							AND  BILLTYPE=@BILLTYPE
             		               execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM
		END     

		IF @SFLAG=1
		BEGIN
			DELETE BANKBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
						AND  BILLTYPE=@BILLTYPE
	                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM

		END

   update  STORECGTHM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CGTH_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CGTH_DEL
      set @flagreturn = 0
   end
end







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG
























----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_CKDB]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG    int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @GOODSNAME    varchar(50)               --明细存货编号
declare @STOREIDEqty NUMERIC(20,10)                          --仓库数量
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @INSTOREID varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @RATE NUMERIC(20,10)                          --数量
declare @UNITQTY NUMERIC(20,10)                          --数量
declare @REFqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @APRICE  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID  varchar(50)
declare @OUTSTOREID varchar(15)               --明细存货编号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @MINBILLDATE DATEtime
declare @MAXBILLDATE DATEtime
declare @B_ID INTEGER
declare @PRICETYPE INTEGER
declare @COUNT   INTEGER
declare @NEGCLOSEOFF   bit
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @JianShu [int] 
declare @MeiJianQty [T_QUANTITY] 
declare @LingTou [T_QUANTITY] 


       SELECT    @NEGCLOSEOFF=(SELECT  NEGCLOSEOFF  FROM   ACCINFO    WHERE   GUID='0001' )           

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
SET  @RETURNSTRING='  '

set @BILLID   = ltrim(rtrim(@BILLID))


     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @BillDate =   (select BillDate  from  STORECKDBM where rtrim(BILLID) = @BILLID)
    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END


if  (select isnull(flagPost,0) from STORECKDBM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CKDB   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STORECKDBM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STORECKDBM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STORECKDBM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STORECKDBM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  SFLAG  from STORECKDBM where rtrim(BILLID) = @BILLID)
     set @INSTOREID  =  (select  VENDORID  from STORECKDBM where rtrim(BILLID) = @BILLID)
     set @OUTSTOREID  =  (select CLIENTID  from STORECKDBM where rtrim(BILLID) = @BILLID)
           IF @INSTOREID = @OUTSTOREID
           BEGIN

	      rollback transaction trans_CKDB
	      set @flagreturn = 0
                    SET @RETURNSTRING='调出仓库和调入仓库不能为同一仓库'
                      RETURN
	END

    declare SM_Consign_CKDBOUT Cursor for Select  ITEMNO,GOODSID, isnull(QUANTITY,0) as qty,isnull(PRICE,0) as PRICE, 
                                                                   REDetailBillFlowID,Isnull(UNITQTY,0) as UNITQTY,PRICETYPE,JianShu,MeiJianQty,LingTou   from STORECKDBD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CKDBOUT

    fetch SM_Consign_CKDBOUT into @ITEMNO,@GOODSID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY ,@PRICETYPE,@JianShu,@MeiJianQty,@LingTou   

    while @@fetch_status = 0            ----开始
    begin
                     set @MeiJianQty =   (select ISNULL(RATE1,0)  from GOODS where  GOODSID = @GOODSID)


                            IF (ISNULL(@JianShu,0)*ISNULL(@MeiJianQty,0)+ISNULL(@LingTou,0)<>@Unitqty) AND (ISNULL(@JianShu,0)<>0 OR ISNULL(@LingTou,0)<>0)
                                     BEGIN
			      rollback transaction trans_CKDB
			      set @flagreturn = 0
                                              SET @RETURNSTRING='件数*每件数量+零头与数量不等，单据不能记帐'
			    close SM_Consign_CKDBOUT
			    deallocate SM_Consign_CKDBOUT
                                          RETURN
			END
                                      IF NOT (exists (select * from STORE where STOREID=@OUTSTOREID))
                                     BEGIN
			      rollback transaction trans_CKDB
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close SM_Consign_CKDBOUT
			    deallocate SM_Consign_CKDBOUT
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@OUTSTOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_CKDB
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_CKDBOUT
			    deallocate SM_Consign_CKDBOUT
                                          RETURN
			END


			declare @FuKuCunOUTQty int    ---1代表数量提示，0代表重量提示
			declare @BiJiaoQTY  NUMERIC(20,10)  ---比较过度用的变量


		        set @FuKuCunOUTQty  = (select optionvalue from accoptions where optionname ='FuKuCunOUTQty')     
		
                        IF    @NEGCLOSEOFF=0 
			BEGIN 
				IF @FuKuCunOUTQty=1
				BEGIN 
	                             	EXEC   GETGOODSIDMEQTY  @OUTSTOREID,@GOODSID,@YYYYMM,@MEQTY=@STOREIDEQTY   OUTPUT
					SET @BiJiaoQTY=@UNITQTY
				END
				ELSE
				BEGIN 
	                             	EXEC   GETGOODSIDEQTY  @OUTSTOREID,@GOODSID,@YYYYMM,@EQTY=@STOREIDEQTY   OUTPUT				
					SET @BiJiaoQTY=@QTY
				END
                                IF @BiJiaoQTY >  ISNULL(@STOREIDEQTY,0)
 		                        BEGIN
                          		                  SET  @GOODSNAME =(SELECT NAME  FROM GOODS WHERE GOODSID=@GOODSID)
				      rollback transaction trans_CKDB
				      set @flagreturn = 0
             		                                 SET @RETURNSTRING='此'+@GOODSNAME+'库存不足不能记帐'
				    close SM_Consign_CKDBOUT
				    deallocate SM_Consign_CKDBOUT
                          		                RETURN
				END
			END
            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)*0.001  from GOODS where  GOODSID = @GOODSID)


---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	



	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@OUTSTOREID ,@qty ,@PRICE ,@REDetailBillFlowID, @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output

	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT)
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     -@QTY,@price,@OUTStoreID,'F',-1,@QTY*@PRICE,null, 
	    0,0 )    
--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格


                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@OUTSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@OUTSTOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@OUTSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@OUTSTOREID,@YYYYMM
				     END

                            END




-------------------其实三种成本价的核算方式都一样  
--------反填成本单价
		IF   @SFLAG=0   --------反填
		BEGIN
			IF @PRICETYPE=1    ----吨
			BEGIN
		                      select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID
			          UPDATE   STORECKDBD  set  UNITPRICE=@APRICE
             			           WHERE CURRENT OF   SM_Consign_CKDBOUT
			END
			IF @PRICETYPE=0    ----数量
			BEGIN
		                      select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID
			          UPDATE   STORECKDBD  set  UNITPRICE=@APRICE*@QTY/@UNITQTY
             			           WHERE CURRENT OF   SM_Consign_CKDBOUT
			END
		
		END

                  
--------------------
    fetch SM_Consign_CKDBOUT into @ITEMNO,@GOODSID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY ,@PRICETYPE,@JianShu,@MeiJianQty,@LingTou   

    END           ------- SM_Consign_CKDBOUT  WHILE

    close SM_Consign_CKDBOUT
    deallocate SM_Consign_CKDBOUT


-----------------------------------------------------以上是出库，以下是入库

    declare SM_Consign_CKDBIN Cursor for Select  ITEMNO,GOODSID,isnull(QUANTITY,0) as qty,isnull(PRICE,0) as PRICE, 
                                                                   REDetailBillFlowID ,UNITQTY ,PRICETYPE   from STORECKDBD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CKDBIN

    fetch SM_Consign_CKDBIN into @ITEMNO,@GOODSID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY  ,@PRICETYPE

    while @@fetch_status = 0            ----开始
    begin
                                      IF NOT (exists (select * from STORE where STOREID=@INSTOREID))
                                     BEGIN
			      rollback transaction trans_CKDB
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close SM_Consign_CKDBIN
			    deallocate SM_Consign_CKDBIN
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@INSTOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_CKDB
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_CKDBIN
			    deallocate SM_Consign_CKDBIN
                                          RETURN
			END



            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)*0.001  from GOODS where  GOODSID = @GOODSID)


---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	


	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@INSTOREID ,@qty ,@PRICE ,@REDetailBillFlowID,  @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output

	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID, MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@INStoreID,'F',1,@QTY*@PRICE,null,
	    0,0)    

	          UPDATE   STORECKDBD  set    DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_CKDBIN
-----------====================2012-09-04 begin

	IF   @INF_COSTINGTYPEID=6 
	Begin

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output

	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID, MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,2,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@INStoreID,'F',1,@QTY*@PRICE,null,
	    0,0)    
	end
--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格

                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@INSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@INSTOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@INSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@INSTOREID,@YYYYMM
				     END

                            END



		IF   @SFLAG=0   --------反填
		BEGIN
			IF @PRICETYPE=1    ----吨
			BEGIN
		                      select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID
			          UPDATE   STORECKDBD  set  UNITPRICE=@APRICE
             			           WHERE CURRENT OF   SM_Consign_CKDBIN
			END
			IF @PRICETYPE=0    ----数量
			BEGIN
		                      select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID
			          UPDATE   STORECKDBD  set  UNITPRICE=@APRICE*@QTY/@UNITQTY
             			           WHERE CURRENT OF   SM_Consign_CKDBIN
			END
		
		END

    fetch SM_Consign_CKDBIN into @ITEMNO,@GOODSID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY  ,@PRICETYPE

    END           ------- SM_Consign_CKDBIN  WHILE

    close SM_Consign_CKDBIN
    deallocate SM_Consign_CKDBIN


   update  STORECKDBM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
   update  STORECKDBD  set   AMT  =  Round(ISNULL(quantity,0)*ISNULL(UNITprice,0),2)               where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STORECKDBD  set   AMT  =  Round(ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)            where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CKDB
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CKDB
      set @flagreturn = 0
   end
end










----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG
















--------------------------------------------------------------------
----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_CKDB_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   

                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --会计年月   
DECLARE @DetailBillFlowID  varchar(8)                   --会计年月   
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @STOREID    varchar(15)               --明细存货编号
declare @REFQTY   NUMERIC(20,10)

declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)

declare @bill_type int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @INSTOREID varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @QUANTITY NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID  varchar(50)
declare @OUTSTOREID varchar(15)               --明细存货编号

declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @B_CODE VARCHAR(25)
declare @PRODUCTDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           


                                              SET @RETURNSTRING='   '


set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STORECKDBM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STORECKDBM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CKDB_DEL   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STORECKDBM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STORECKDBM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STORECKDBM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STORECKDBM where rtrim(BILLID) = @BILLID)
     set @INSTOREID  =  (select CLIENTID  from STORECKDBM where rtrim(BILLID) = @BILLID)
     set @OUTSTOREID  =  (select VENDORID  from STORECKDBM where rtrim(BILLID) = @BILLID)

    declare SM_Consign_CKDBOUT_DEL Cursor for Select  ITEMNO,GOODSID,STOREID,REDetailBillFlowID ,QUANTITY ,DetailBillFlowID   from STORECKDBD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CKDBOUT_DEL

    fetch SM_Consign_CKDBOUT_DEL into @ITEMNO,@GOODSID,@STOREID,@REDetailBillFlowID ,@QUANTITY,@DetailBillFlowID

    while @@fetch_status = 0            ----开始
    begin
	            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
             		  DELETE    DetailBillFlow    WHERE ITEMNO=@ITEMNO  AND BILLID=@BILLID  AND GOODSID=@GOODSID  AND BILLTYPE=5

                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@OUTSTOREID,@YYYYMM
	                             execute      APRICECACULATOR_STORE   @GOODSID,@INSTOREID,@YYYYMM
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@OUTSTOREID,@YYYYMM
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@INSTOREID,@YYYYMM
                            END


                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@OUTSTOREID,@YYYYMM
	                             execute      APRICECACULATOR_STORE   @GOODSID,@INSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
	                             execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@OUTSTOREID,@YYYYMM
	                             execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@INSTOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@OUTSTOREID,@YYYYMM
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@INSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
             		                execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@OUTSTOREID,@YYYYMM
             		                execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@INSTOREID,@YYYYMM
				     END

                            END


		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@OUTSTOREID  AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@INSTOREID  AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM

      fetch SM_Consign_CKDBOUT_DEL  into @ITEMNO,@GOODSID,@STOREID,@REDetailBillFlowID ,@QUANTITY,@DetailBillFlowID

    END           ------- SM_Consign_CKDBOUT  WHILE

    close SM_Consign_CKDBOUT_DEL
    deallocate SM_Consign_CKDBOUT_DEL



   update  STORECKDBM  set  flagPost = 0      where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CKDB_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CKDB_DEL
      set @flagreturn = 0
   end
end








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG

















--------------------------------------------------------------------
----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_CKPD]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @REDetailBillFlowID varchar(15)               --明细存货编号

declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)
declare @bill_type int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @RATE  NUMERIC(20,10)               --含税单价
declare @APRICE  NUMERIC(20,10)               --含税单价
declare @PRICE00  NUMERIC(20,10)               --含税单价
declare @REFQTY  NUMERIC(20,10)               --含税单价
declare @unitqty  NUMERIC(20,10)               --含税单价
declare @UNITPRICE  NUMERIC(20,10)               --含税单价
declare @MINBILLDATE DATEtime
declare @MAXBILLDATE DATEtime

declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @B_CODE VARCHAR(25)
declare @V_DATE DATEtime
declare @B_ID INTEGER
declare @COUNT INTEGER
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间


       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @BillDate =   (select BillDate  from STORECKPDM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END

if  (select isnull(flagPost,0) from STORECKPDM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CKPD   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STORECKPDM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STORECKPDM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STORECKPDM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STORECKPDM where rtrim(BILLID) = @BILLID)

    declare SM_Consign_CKPD Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(PRICE,0) as PRICE, 
                                                                   REDetailBillFlowID,ISNULL(UNITQTY,0) AS UNITQTY,ISNULL(UNITPRICE,0) AS UNITPRICE  from STORECKPDD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CKPD

    fetch SM_Consign_CKPD into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID ,@UNITQTY,@UNITPRICE

    while @@fetch_status = 0            ----开始
    begin

                                      IF NOT (exists (select * from STORE where STOREID=@STOREID))
                                     BEGIN
			      rollback transaction trans_CKPD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close SM_Consign_CKPD
			    deallocate SM_Consign_CKPD
                                          RETURN
			END

                                      IF exists (select * from STORE where STOREID=@STOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_CKPD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_CKPD
			    deallocate SM_Consign_CKPD
                                          RETURN
			END



            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)

	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE ,@REDetailBillFlowID  , @BILLID 
		IF @QTY-@price>0
		BEGIN

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output

	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID, MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT  )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY-@price,@price00,Null,Null,@INF_COSTINGTYPEID, @UNITQTY-@UNITPRICE,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     0,0 )    

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output

	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID, MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT  )
	    Values
	    (@NEWID,@BILLYYYYMM,2,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY-@price,@price00,Null,Null,@INF_COSTINGTYPEID, @UNITQTY-@UNITPRICE,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     0,0 )    

		end

		IF @QTY-@price<0
		BEGIN

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output

	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID, MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT  )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @price-@QTY,@price00,Null,Null,@INF_COSTINGTYPEID, @UNITPRICE-@UNITQTY,
	     @QTY,@price,@StoreID,'F',-1,@QTY*@PRICE,null, 
	     0,0 )    


		end




                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END


--------反填成本单价

    fetch SM_Consign_CKPD into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID ,@UNITQTY,@UNITPRICE

    END           ------- SM_Consign_CKPD  WHILE

    close SM_Consign_CKPD
    deallocate SM_Consign_CKPD
   update  STORECKPDM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CKPD
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CKPD
      set @flagreturn = 0
   end
end













----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_CKPD_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                    @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 

declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @REDetailBillFlowID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
DECLARE @INF_COSTINGTYPEID   INT
DECLARE @REFQTY   NUMERIC(20,10)
declare @QUANTITY  NUMERIC(20,10)
declare @PRICE  NUMERIC(20,10)
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STORECKPDM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STORECKPDM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CKPD_DEL   --事物开始


    declare SM_Consign_CKPD_DEL Cursor for Select GOODSID,DetailBillFlowID,STOREID,QUANTITY,PRICE,REDetailBillFlowID    from STORECKPDD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CKPD_DEL

    fetch SM_Consign_CKPD_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@QUANTITY,@PRICE,@REDetailBillFlowID

    while @@fetch_status = 0            ----开始
    begin
                             DELETE   DetailBillFlow   WHERE  ID=@DetailBillFlowID
       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID

                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

--------------------
		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@STOREID AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
      fetch SM_Consign_CKPD_DEL into  @GOODSID,@DetailBillFlowID,@STOREID,@QUANTITY,@PRICE,@REDetailBillFlowID

    END           ------- SM_Consign_CKPD_DEL  WHILE

    close SM_Consign_CKPD_DEL
    deallocate SM_Consign_CKPD_DEL

                            DELETE   DetailBillFlow     WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND (YYYYMMBILL in (1,2)) AND BILLTYPE=6

   update  STORECKPDM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CKPD_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CKPD_DEL
      set @flagreturn = 0
   end
end








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG


















----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_CSH]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ITEMNO varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @RATE NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @UNITQTY  NUMERIC(20,10)               --含税单价
declare @SUMAMT  NUMERIC(20,10)               --含税单价
declare @TAXRATE NUMERIC(20,10)                          --单据总金额

declare @BILLTYPE INTEGER
declare @PRICETYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @STOREHSFS   INTEGER
declare @JianShu [int] 
declare @MeiJianQty [T_QUANTITY] 
declare @LingTou [T_QUANTITY] 

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

if  (select isnull(flagPost,0) from STORECSHM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CSH   --事物开始

--     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')      
     set @YYYYMM   = '199912'
 
     set @INOUTFLAG =   (select INOUTFLAG from STORECSHM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STORECSHM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STORECSHM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STORECSHM where rtrim(BILLID) = @BILLID)
   	 SELECT @SUMAMT=0


    declare SM_Consign_CSH Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(UNITPRICE,0) as PRICE,
                                                                  PRICETYPE,ISNULL(UNITQTY,0)   AS UNITQTY,JianShu,MeiJianQty,LingTou   from STORECSHD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CSH

    fetch SM_Consign_CSH into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@PRICETYPE,@UNITQTY,@JianShu,@MeiJianQty,@LingTou

    while @@fetch_status = 0            ----开始
    begin
                     set @MeiJianQty =   (select ISNULL(RATE1,0)  from GOODS where  GOODSID = @GOODSID)


                            IF (ISNULL(@JianShu,0)*ISNULL(@MeiJianQty,0)+ISNULL(@LingTou,0)<>@Unitqty) AND (ISNULL(@JianShu,0)<>0 OR ISNULL(@LingTou,0)<>0)
                                     BEGIN
			      rollback transaction trans_CSH
			      set @flagreturn = 0
                                              SET @RETURNSTRING='件数*每件数量+零头与数量不等，单据不能记帐'
			    close SM_Consign_CSH
			    deallocate SM_Consign_CSH
                                          RETURN
			END



            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)



---------------根据理算系数核算重量与数量
            set @RATE =   (select ISNULL(RATE,0)*0.001  from GOODS where  GOODSID = @GOODSID)

---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	

	IF @PRICETYPE=0  
	BEGIN
		IF   @QTY<>0
		BEGIN
		SET  @PRICE=(@UNITQTY*@PRICE)/@QTY
		END

	END





                                        IF NOT (exists (select * from STORE where STOREID=@STOREID))
                                     BEGIN
			      rollback transaction trans_CSH
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close SM_Consign_CSH
			    deallocate SM_Consign_CSH
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@STOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_CSH
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_CSH
			    deallocate SM_Consign_CSH
                                          RETURN
			END



	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE ,@DetailBillFlowID  , @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID, 
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT ,MINQTY)
	    Values
	    (@NEWID,@YYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID,
	     @QTY,@price,@StoreID,'F',@inoutFlag,@QTY*@PRICE,null,
	     0,0  ,@UNITQTY)    
	          UPDATE   STORECSHD  set    DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_CSH



-----------====================2012-09-04 begin

	IF   @INF_COSTINGTYPEID=6 
	Begin

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID, 
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT ,MINQTY)
	    Values
	    (@NEWID,@YYYYMM,2,@BillDate,@BillType,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID,
	     @QTY,@price,@StoreID,'F',@inoutFlag,@QTY*@PRICE,null,
	     0,0  ,@UNITQTY)    
	END

--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

--------------------
    fetch SM_Consign_CSH into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@PRICETYPE,@UNITQTY,@JianShu,@MeiJianQty,@LingTou

    END           ------- SM_Consign_CSH  WHILE

    close SM_Consign_CSH
    deallocate SM_Consign_CSH
   update  STORECSHM  set  flagPost = 1,YYYYMM =@YYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CSH
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CSH
      set @flagreturn = 0
   end
end














----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_CSH_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 

declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @STOREHSFS   INTEGER

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @YYYYMMBILL =   (select YYYYMM  from STORECSHM where rtrim(BILLID) = @BILLID)
       IF   @YYYYMM<>  @YYYYMMBILL
       BEGIN
       SET @RETURNSTRING=' 帐套启用后，仓库初始化单据不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  ((select isnull(flagPost,0) from STORECSHM where ltrim(rtrim(BILLID)) = @BILLID ) = 0) or (not (@YYYYMM=@YYYYMMBILL))
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CSH_DEL   --事物开始

     DELETE   DetailBillFlow 
     UPDATE  GOODS  SET APRICE=0
     DELETE   GOODSINIT

   update  STORECSHM  set  flagPost = 0    --------where ltrim(rtrim(BILLID)) = @BILLID 
     
     -------------仓库初始化单据取消记帐是全部取消记帐
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CSH_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CSH_DEL
      set @flagreturn = 0
   end
end





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG




















CREATE PROCEDURE [dbo].[STORE_CW_PingZheng]  
                 (
                  @BILLID varchar(22),      ---单据编号  
                  @BILLPost varchar(20),      ---单据编号  
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @Detailflag int                     --业务类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @Debit NUMERIC(20,2)
declare @ItemBM  varchar(50)               --明细存货编号
declare @NewItemBM varchar(20)               --明细存货编号
declare @PrevNO varchar(20)               --明细存货编号
declare @CredCode   varchar(20)               --明细存货编号
declare @CredTypeName   varchar(20)               --明细存货编号
declare @DuiFangKeMu   varchar(30)               --明细存货编号
declare @CredTypeID   int
declare @credit NUMERIC(20,2)
declare @BILLCODE VARCHAR(25)
declare @Brief VARCHAR(200)
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER


SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

     set @BillDate =   (select BillDate  from CW_PingZhengM where rtrim(BILLID) = @BILLID)
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='CW_YYYYMM')     


if  (select isnull(flagPost,0) from CW_PingZhengM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CW_PingZheng   --事物开始

--     set @BillCode =   (select CODE from CW_PingZhengM where rtrim(BILLID) = @BILLID)
     set @Credcode =   (select Credcode from CW_PingZhengM where rtrim(BILLID) = @BILLID)
     set @CredTypeID =   (select CredTypeID from CW_PingZhengM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from CW_PingZhengM where rtrim(BILLID) = @BILLID)

    select  @CredTypeName=Name from CredType where CredTypeID=@CredTypeID

	set  @BillCode=@CredTypeName+@Credcode

    declare SM_Consign_CW_PingZheng Cursor for Select  ITEMNO,ItemBM,Debit, credit,Brief   from CW_PingZhengD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CW_PingZheng

    fetch SM_Consign_CW_PingZheng into @ITEMNO,@ItemBM,@Debit,@credit,@Brief

    while @@fetch_status = 0            ----开始
    begin

-------缺少检测仓库  明日解决
----(itembm not in (select prevno from iteminfo) 

                      IF NOT (exists (select * from iteminfo where Detailflag=1 and ItemBM = @ItemBM))
                       BEGIN
			      set @flagreturn = 0
                             SET @RETURNSTRING='科目不存在或为空或为非明细科目，单据不能记帐'
			    close SM_Consign_CW_PingZheng
			    deallocate SM_Consign_CW_PingZheng
			      rollback transaction trans_CW_PingZheng

                            RETURN
			END
--------------------判断现金银行日记账

--------------------固化会计科目编码第一级为4位		    

			set @DuiFangKeMu=' '

		    if  substring(@ItemBM,1,4)='1001'  or substring(@ItemBM,1,4)='1002'
			begin

			select @DuiFangKeMu=ItemBM from CW_PingZhengD  where rtrim(BILLID) = @BILLID  and   ItemBM<>@ItemBM  and (Debit=@credit OR  credit=@Debit )

			end


--------------------

		    set @NewItemBM=@ItemBM
			
		    select @PrevNO='9999AAAA'

		
	      while  (@PrevNO<>'0000') 
	      begin
	        select @Detailflag=Detailflag from ItemInfo where ItemBM=@NewItemBM


			    EXEC  CW_BillFlow_insert_YYYYMM  @NewItemBM
	
		            execute  GETKEYVALUE     'CW_BillFlow',@R_KeyValue = @NEWID output
			    insert into CW_BillFlow 
			    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLID,BILLCODE,ITEMNO,ItemBM,
			     Debit,credit,Brief,Detailflag,duifangKemu  )
			    Values
			    (@NEWID,@YYYYMM,1,@BillDate,@BillID,@BillCode,@itemNo,@NewItemBM,
			     @Debit,@credit,@Brief,@Detailflag,@duifangKemu )    

		             execute   CW_CACULATOR_YYYYMM @NewItemBM,@YYYYMM

	        select @PrevNO=PrevNO from ItemInfo where ItemBM=@NewItemBM


		SET @NewItemBM=@PrevNO

	     end          -------while  @PrevNO<>'0000' 



--------------------
    fetch SM_Consign_CW_PingZheng into @ITEMNO,@ItemBM,@Debit,@credit,@Brief

    END           ------- SM_Consign_CW_PingZheng  WHILE

    close SM_Consign_CW_PingZheng
    deallocate SM_Consign_CW_PingZheng

   update  CW_PingZhengM  set  flagPost = 1,BILLPost=@BillPost         where ltrim(rtrim(BILLID)) = @BILLID 
    

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CW_PingZheng
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CW_PingZheng
      set @flagreturn = 0
   end
end












----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG















----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[STORE_CW_PingZheng_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @ItemBM varchar(20)               --明细存货编号
declare @NewItemBM varchar(20)               --明细存货编号
declare @PrevNO varchar(20)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @Debit    varchar(15)               --明细存货编号
declare @credit   varchar(30)                     --序列号
declare @VENDORID   varchar(30)                     --序列号
declare @Detailflag   INT
declare @VENDORFLAG   INT
declare @SFLAG   INT
declare @REFQTY   NUMERIC(20,10)
declare @STOREHSFS   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER

                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='CW_YYYYMM')       
     set @BILLDate =  (select BILLDate  from CW_PingZhengM where rtrim(BILLID) = @BILLID)

if  (select isnull(flagPost,0) from CW_PingZhengM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_CW_PingZheng_DEL   --事物开始

     DELETE   CW_BILLFLOW     WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 

    declare SM_Consign_CW_PingZheng_DEL Cursor for Select ItemBM,credit,Debit,BILLID    from CW_PingZhengD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_CW_PingZheng_DEL

    fetch SM_Consign_CW_PingZheng_DEL into @ItemBM,@credit,@Debit,@BILLID

    while @@fetch_status = 0            ----开始
    begin

		    set @NewItemBM=@ItemBM
			
		    select @PrevNO='9999AAAA'

		
	      while  (@PrevNO<>'0000') 
	      begin
	        select @Detailflag=Detailflag from ItemInfo where ItemBM=@NewItemBM

		      execute   CW_CACULATOR_YYYYMM @NewItemBM,@YYYYMM
	
	        select @PrevNO=PrevNO from ItemInfo where ItemBM=@NewItemBM


		SET @NewItemBM=@PrevNO

	     end          -------while  @PrevNO<>'0000' 



    fetch SM_Consign_CW_PingZheng_DEL into @ItemBM,@credit,@Debit,@BILLID

    END           ------- SM_Consign_CW_PingZheng_DEL  WHILE

    close SM_Consign_CW_PingZheng_DEL
    deallocate SM_Consign_CW_PingZheng_DEL


   update  CW_PingZhengM  set  flagPost = 0 ,BILLPost=NULL   where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_CW_PingZheng_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_CW_PingZheng_DEL
      set @flagreturn = 0
   end
end








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_Calculate_Aprice]  
                 (
                              @Curr_YYYYMM   varchar(20),   --传入当前会计期间
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @BILLID  varchar(10)                   --会计年月     
declare @SFLAG  INT
declare @PRICETYPE  INT

declare @APRICE  NUMERIC(20,10) 
declare @QTY  NUMERIC(20,10) 
declare @unitQTY  NUMERIC(20,10) 

--           WAITFOR   DELAY   '0:00:10'

     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_Calculate_Aprice   --事物开始


    declare SM_Calculate_Aprice Cursor for Select DetailBillFlowID    from STOREXSCKD where BILLID in (select BILLID  from STOREXSCKM   where  YYYYMM=@Curr_YYYYMM) 

    Open SM_Calculate_Aprice

    fetch SM_Calculate_Aprice into    @DetailBillFlowID

    while @@fetch_status = 0            ----开始
    begin
	                 SELECT  @APRICE =INPRICE    FROM DETAILBILLFLOW  
             		               WHERE ID= @DETAILBILLFLOWID
                              if  @APRICE is null
                              begin
                                      set @APRICE=0.00
		   end
               UPDATE   STOREXSCKD  set    APRICE=@APRICE    WHERE CURRENT OF  SM_Calculate_Aprice

--------------------
      fetch SM_Calculate_Aprice   into @DetailBillFlowID      

    END           ------- SM_Calculate_Aprice  WHILE

    close SM_Calculate_Aprice
    deallocate SM_Calculate_Aprice
    
-------------------------------------------------------============
    declare SM_Calculate_Aprice Cursor for Select DetailBillFlowID    from STOREXSTHD where BILLID in (select BILLID  from STOREXSTHM   where  YYYYMM=@Curr_YYYYMM) 

    Open SM_Calculate_Aprice

    fetch SM_Calculate_Aprice into    @DetailBillFlowID

    while @@fetch_status = 0            ----开始
    begin
	                 SELECT  @APRICE =INPRICE    FROM DETAILBILLFLOW  
             		               WHERE ID= @DETAILBILLFLOWID
                              if  @APRICE is null
                              begin
                                      set @APRICE=0.00
		   end
               UPDATE   STOREXSTHD  set    APRICE=@APRICE    WHERE CURRENT OF  SM_Calculate_Aprice

--------------------
      fetch SM_Calculate_Aprice   into @DetailBillFlowID      

    END           ------- SM_Calculate_Aprice  WHILE

    close SM_Calculate_Aprice
    deallocate SM_Calculate_Aprice
    
-------------------------------------------------------============销售出库单和销售退货单反填“吨”价格
    declare SM_Calculate_Aprice Cursor for Select DetailBillFlowID,BILLID,PRICETYPE,quantity,unitqty    from STOREQTCKD where BILLID in (select BILLID  from STOREQTCKM   where  YYYYMM=@Curr_YYYYMM) 

    Open SM_Calculate_Aprice

    fetch SM_Calculate_Aprice into    @DetailBillFlowID,@BILLID,@PRICETYPE,@qty,@unitqty

    while @@fetch_status = 0            ----开始
    begin
	                 SELECT  @APRICE =INPRICE    FROM DETAILBILLFLOW  
             		               WHERE ID= @DETAILBILLFLOWID
                              if  @APRICE is null
                              begin
                                      set @APRICE=0.00
		   end
		select @SFLAG=(SELECT SFLAG  FROM STOREQTCKM  WHERE  BILLID=@BILLID)
		IF   @SFLAG=0   --------反填
		BEGIN
	                   	   select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@DetailBillFlowID
			IF @PRICETYPE=1    ----吨
			BEGIN
			          UPDATE     STOREQTCKD     set    APRICE=@APRICE,UNITPRICE=@APRICE
             		    	    	   WHERE CURRENT OF SM_Calculate_Aprice
			END

			IF @PRICETYPE=0    ----数量
			BEGIN
			          UPDATE     STOREQTCKD     set    APRICE=@APRICE,UNITPRICE=@APRICE*@QTY/@UNITQTY
             		    	    	   WHERE CURRENT OF SM_Calculate_Aprice
			END

		END

               UPDATE   STOREQTCKD  set    APRICE=@APRICE    WHERE CURRENT OF  SM_Calculate_Aprice

--------------------
    fetch SM_Calculate_Aprice into    @DetailBillFlowID,@BILLID,@PRICETYPE,@qty,@unitqty

    END           ------- SM_Calculate_Aprice  WHILE

    close SM_Calculate_Aprice
    deallocate SM_Calculate_Aprice
    
-------------------------------------------------------============
-------------------------------------------------------============
    declare SM_Calculate_Aprice Cursor for Select DetailBillFlowID,BILLID,PRICETYPE,quantity,unitqty    from STORECKDBD where BILLID in (select BILLID  from STORECKDBM   where  YYYYMM=@Curr_YYYYMM) 

    Open SM_Calculate_Aprice

    fetch SM_Calculate_Aprice into    @DetailBillFlowID,@BILLID,@PRICETYPE,@qty,@unitqty

    while @@fetch_status = 0            ----开始
    begin
	                 SELECT  @APRICE =INPRICE    FROM DETAILBILLFLOW  
             		               WHERE ID= @DETAILBILLFLOWID
                              if  @APRICE is null
                              begin
                                      set @APRICE=0.00
		   end
		select @SFLAG=(SELECT SFLAG  FROM STORECKDBM  WHERE  BILLID=@BILLID)
		IF   @SFLAG=0   --------反填
		BEGIN
	                   	   select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@DetailBillFlowID
			IF @PRICETYPE=1    ----吨
			BEGIN
			          UPDATE     STORECKDBD     set    APRICE=@APRICE,UNITPRICE=@APRICE
             		    	    	   WHERE CURRENT OF SM_Calculate_Aprice
			END

			IF @PRICETYPE=0    ----数量
			BEGIN
			          UPDATE     STORECKDBD     set    APRICE=@APRICE,UNITPRICE=@APRICE*@QTY/@UNITQTY
             		    	    	   WHERE CURRENT OF SM_Calculate_Aprice
			END

		END

               UPDATE   STORECKDBD  set    APRICE=@APRICE    WHERE CURRENT OF  SM_Calculate_Aprice

--------------------
    fetch SM_Calculate_Aprice into    @DetailBillFlowID,@BILLID,@PRICETYPE,@qty,@unitqty

    END           ------- SM_Calculate_Aprice  WHILE

    close SM_Calculate_Aprice
    deallocate SM_Calculate_Aprice
    
-------------------------------------------------------============
-------------------------------------------------------============


   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_Calculate_Aprice
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_Calculate_Aprice
      set @flagreturn = 0
   end





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG















--------------------------------------------------------------------

CREATE PROCEDURE [STORE_FYKZ]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。


declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)

declare @bill_type int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @CLIENTID   varchar(15)               --明细存货编号
declare @VendorID   varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @SUMAMT NUMERIC(20,10)                          --数量
declare @refqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @INBANKID VARCHAR(25)
declare @BILLDATE DATEtime
declare @MINBILLDATE DATEtime
declare @MAXBILLDATE DATEtime
declare @B_CODE VARCHAR(25)
declare @V_DATE DATEtime
declare @ClientFlag int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @B_ID INTEGER
declare @STOREHSFS   INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @YYYYMM_FLAG  INTEGER

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

   declare  @PREV_YYYYMM          varchar(6)  -- 上一个会计年月
   declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     

     set @BillDate =   (select BillDate  from STOREFYKZM where rtrim(BILLID) = @BILLID)
    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END



if  (select isnull(flagPost,0) from STOREFYKZM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_FYKZ   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREFYKZM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREFYKZM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREFYKZM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREFYKZM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  SFLAG  from STOREFYKZM where rtrim(BILLID) = @BILLID)
     set @INBANKID =   (select  VENDORID  from STOREFYKZM where rtrim(BILLID) = @BILLID)
     set @ClientFLAG =   (select  ISNULL(ClientFLAG,1)   from STOREFYKZM where rtrim(BILLID) = @BILLID)
     set @CLIENTID =   (select CLIENTID  from STOREFYKZM where rtrim(BILLID) = @BILLID)



                                      IF NOT (exists (select * from BANK where BANKID=@INBANKID))
                                     BEGIN
			      rollback transaction trans_FYKZ
			      set @flagreturn = 0
                                              SET @RETURNSTRING='银行科目不能为空或银行科目不存在，单据不能记帐'
                                          RETURN
			END
   	 SELECT @SUMAMT= (SELECT SUM(QUANTITY)  FROM  STOREFYKZD   where rtrim(BILLID) = @BILLID)

------------------------------以下是解决科目帐的算法
            IF   (not exists(select *  from BANKBILLFLOW  where 
             		                                    (rtrim(BANKID) = @INBANKID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@INBANKID,
		     0,0,Null,
		     @inoutFlag,0  )    
            END      ------IF   END
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@INBANKID,
		     0,@SUMAMT,Null,
		     -1,0  )    
                            execute      BANK_CACULATOR_YYYYMM   @INBANKID,@YYYYMM
------------------------------------



	IF  @ClientFLAG=1  and @CLIENTID<>''
	BEGIN
	            IF   (not exists(select *  from CLIENTBILLFLOW  where 
             		                                    (rtrim(CLIENTID) = @CLIENTID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE, CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode, @CLIENTID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE, CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode, @CLIENTID,
		     0,@SUMAMT,Null,
		     1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM
	END         ---------------IF @SFLAG=0



	IF  @ClientFLAG=0  and @CLIENTID<>''
	BEGIN

	      SET @VendorID=@ClientID
	            IF   (not exists(select *  from VENDORBILLFLOW  where 
             		                                    (rtrim(VENDORID) = @VENDORID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
	             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,-@SUMAMT,Null,
		     1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM

	END     ----------------     IF @SFLAG=0







------------------------------------

   update  STOREFYKZM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_FYKZ
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_FYKZ
      set @flagreturn = 0
   end
end







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG















----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_FYKZ_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 

declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @BANKID    varchar(15)               --明细存货编号
declare @INBANKID    varchar(15)               --明细存货编号
declare @CLIENTID   varchar(30)                     --序列号
declare @VendorID   varchar(30)                     --序列号
declare @INF_COSTINGTYPEID   INT
declare @REFQTY   NUMERIC(20,10)
declare @ClientFlag int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STOREFYKZM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREFYKZM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_FYKZ_DEL   --事物开始


	     set @INBANKID =   (select  VENDORID  from STOREFYKZM where rtrim(BILLID) = @BILLID)

     set @ClientFLAG =   (select  ISNULL(ClientFLAG,1)   from STOREFYKZM where rtrim(BILLID) = @BILLID)
     set @CLIENTID =   (select CLIENTID  from STOREFYKZM where rtrim(BILLID) = @BILLID)

		DELETE   BANKBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=13
                            execute      BANK_CACULATOR_YYYYMM   @INBANKID,@YYYYMM


	IF      @ClientFlag=1
	BEGIN
		DELETE   CLIENTBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=13
                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM
	END

		IF  @ClientFlag=0
		BEGIN

		      SET @VendorID=@ClientID
			DELETE   VENDORBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=13
             		               execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM
	                             DELETE  VENDORBILLFLOW    WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 AND BILLTYPE=13
--------------------------------------以上上全部删除单据  是解决多次记帐失败的问题

		END     



   update  STOREFYKZM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_FYKZ_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_FYKZ_DEL
      set @flagreturn = 0
   end
end







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG

















--------------------------------------------------------------------

CREATE PROCEDURE [STORE_GJRK]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---是否现款标志
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @VENDORID   varchar(15)               --明细存货编号
declare @bankID   varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @RATE NUMERIC(20,10)                          --单据总金额

declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @SUMAMT NUMERIC(20,10)                          --单据总金额
declare @refqty NUMERIC(20,10)                          --引用数量
declare @UNITQTY NUMERIC(20,10)                          --引用数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @lcode varchar(30)                     --序列号
declare @REDetailBillFlowID varchar(30)                     --序列号
declare @BILLTYPE INTEGER
declare @status INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @JianShu [int] 
declare @MeiJianQty [T_QUANTITY] 
declare @LingTou [T_QUANTITY] 


       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

     set @BillDate =   (select BillDate  from STOREGJRKM where rtrim(BILLID) = @BILLID)
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     

    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END

if  (select isnull(flagPost,0) from STOREGJRKM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_GJRK   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREGJRKM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREGJRKM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREGJRKM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREGJRKM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREGJRKM where rtrim(BILLID) = @BILLID)
     set @VENDORID =   (select  VENDORID  from STOREGJRKM where rtrim(BILLID) = @BILLID)
     set @BANKID =   (select BANKID  from STOREGJRKM where rtrim(BILLID) = @BILLID)   ---------付款银行
	     set @STATUS =   (select STATUS  from STOREGJRKM where rtrim(BILLID) = @BILLID)

                                      IF NOT (exists (select * from VENDOR where VENDORID=@VENDORID))
                                     BEGIN
			      rollback transaction trans_GJRK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='供应商不能为空或供应商不存在，单据不能记帐'
                                          RETURN
			END

   	 SELECT @SUMAMT= (SELECT SUM(ROUND(unitprice*QUANTITY,2)) FROM   STOREGJRKD  where rtrim(BILLID) = @BILLID)


    declare SM_Consign_GJRK Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(unitPRICE,0)    as PRICE, 
                                                                 DetailBillFlowID,REDetailBillFlowID,isnull(UNITQTY,0) AS UNITQTY,JianShu,MeiJianQty,LingTou    from STOREGJRKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_GJRK

    fetch SM_Consign_GJRK into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE, @DetailBillFlowID,@REDetailBillFlowID,@UNITQTY,@JianShu,@MeiJianQty,@LingTou

    while @@fetch_status = 0            ----开始
    begin

-------缺少检测仓库  明日解决
                            IF (ISNULL(@JianShu,0)*ISNULL(@MeiJianQty,0)+ISNULL(@LingTou,0)<>@Unitqty) AND (ISNULL(@JianShu,0)<>0 OR ISNULL(@MeiJianQty,0)<>0 OR ISNULL(@LingTou,0)<>0)
                                     BEGIN
			      rollback transaction trans_GJRK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='件数*每件数量+零头与数量不等，单据不能记帐'
			    close SM_Consign_GJRK
			    deallocate SM_Consign_GJRK
                                          RETURN
			END


                                      IF NOT (exists (select * from STORE where STOREID=@STOREID))
                                     BEGIN
			      rollback transaction trans_GJRK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close SM_Consign_GJRK
			    deallocate SM_Consign_GJRK
                                          RETURN
			END

            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)*0.001  from GOODS where  GOODSID = @GOODSID)


---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	




	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE  ,@DetailBillFlowID,  @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID, MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT  )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     isnull(@REFQTY,0),0 )    
	          UPDATE   STOREGJRKD  set    DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_GJRK


-----------====================2012-09-04 begin

	IF   @INF_COSTINGTYPEID=6 
	Begin

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID, MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT  )
	    Values
	    (@NEWID,@BILLYYYYMM,2,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     isnull(@REFQTY,0),0 )    

-----///===	update DetailBillFlow  where ID=@NEWID
	END

--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END


--------------------
    fetch SM_Consign_GJRK into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE, @DetailBillFlowID,@REDetailBillFlowID,@UNITQTY,@JianShu,@MeiJianQty,@LingTou

    END           ------- SM_Consign_GJRK  WHILE

    close SM_Consign_GJRK
    deallocate SM_Consign_GJRK

-----------------------以上是解决仓库记帐问题，以下是应付帐款的问题

----------------------判断是否存在在估入库供应商，如果没有则系统自动建立
 
		   if not exists (select  * FROM VENDOR  WHERE VENDORID='AAAAAAAA')
		  BEGIN

			select  @lcode= max(lcode)  from area
			INSERT INTO   VENDOR  (VENDORID,CODE,NAME,areaid)
			    Values   ('AAAAAAAA','ZGRKCODE','在估入库',@lcode)

		  END

		select  @vendorid='AAAAAAAA'

	            IF   (not exists(select *  from VENDORBILLFLOW  where 
             		                                    (rtrim(VENDORID) = @VENDORID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
	             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,@SUMAMT,Null,
		     1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM


-----------------------------
   update  STOREGJRKM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_GJRK
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_GJRK
      set @flagreturn = 0
   end
end













----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_GJRK_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @REBILLID    varchar(15)               --明细存货编号
declare @VENDORID   varchar(30)                     --序列号
declare @billtype   INT
declare @STATUS   INT
declare @SFLAG   INT
declare @INF_COSTINGTYPEID  INT                ---本期期初加权价
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BillDate =   (select BillDate  from STOREGJRKM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREGJRKM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_GJRK_DEL   --事物开始

	SELECT @VENDORID=VENDORID    FROM STOREGJRKM  where rtrim(BILLID) = @BILLID 
	     set @BillType =   (select BillType  from STOREGJRKM where rtrim(BILLID) = @BILLID)
	     set @STATUS =   (select STATUS  from STOREGJRKM where rtrim(BILLID) = @BILLID)
	     set @REBILLID=   (select REFERBILLCODE  from STOREGJRKM where rtrim(BILLID) = @BILLID)


			IF exists(select   ITEMNO   FROM    STOREGJRKD  where rtrim(BILLID) = @BILLID  AND  ITEMNO  IN (SELECT  REGJRKITEMNO   FROM    STORECGRKD ))
			BEGIN
                                              SET @RETURNSTRING=' 此估价入库单已经被采购入库单引用不能取消记帐  '
			      rollback transaction trans_GJRK_DEL
			      set @flagreturn = 0
                                         RETURN
			END

			IF @STATUS=1
			BEGIN
                                              SET @RETURNSTRING=' 此估价入库单是由被采购入库单生成不能取消记帐  '
			      rollback transaction  trans_GJRK_DEL
			      set @flagreturn = 0
                                         RETURN
			END


    declare SM_Consign_GJRK_DEL Cursor for Select GOODSID,DetailBillFlowID,STOREID,BILLID    from STOREGJRKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_GJRK_DEL

    fetch SM_Consign_GJRK_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@BILLID

    while @@fetch_status = 0            ----开始
    begin

                             DELETE   DetailBillFlow     WHERE  ID=@DetailBillFlowID
--------------------------------------以上是删除一条单据明细
       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@STOREID AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
    fetch SM_Consign_GJRK_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@BILLID

    END           ------- SM_Consign_GJRK_DEL  WHILE

    close SM_Consign_GJRK_DEL
    deallocate SM_Consign_GJRK_DEL

                             DELETE   DetailBillFlow     WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND (YYYYMMBILL in (1,2)) AND BILLTYPE=@billtype
--------------------------------------以上上全部删除单据  是解决多次记帐失败的问题

----------------------------
	     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREGJRKM where rtrim(BILLID) = @BILLID)
	     set @BANKID =   (select BANKID  from STOREGJRKM where rtrim(BILLID) = @BILLID)   ---------付款银行

		SELECT @VENDORID ='AAAAAAAA'
		
			DELETE   VENDORBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@BILLTYPE
             		               execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM
	                             DELETE  VENDORBILLFLOW    WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 AND BILLTYPE=@billtype



   update  STOREGJRKM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_GJRK_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_GJRK_DEL
      set @flagreturn = 0
   end
end








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG









-------------------------此过程除了--------------删除单据
CREATE PROCEDURE [STORE_GJRK_DEL_CGRK]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @REBILLID    varchar(15)               --明细存货编号
declare @VENDORID   varchar(30)                     --序列号
declare @billtype   INT
declare @STATUS   INT
declare @SFLAG   INT
declare @REFQTY   NUMERIC(20,10)

set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       

     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_GJRK_DEL_CGRK  --事物开始

	     set @BillType =   (select BillType  from STOREGJRKM where rtrim(BILLID) = @BILLID)

                   DELETE   DetailBillFlow     WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 AND BILLTYPE=@billtype

	     set @BANKID =   (select BANKID  from STOREGJRKM where rtrim(BILLID) = @BILLID)   ---------付款银行

		              SELECT @VENDORID ='AAAAAAAA'
		
			DELETE   VENDORBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@BILLTYPE
             		               execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM

	  DELETE   STOREGJRKM      where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_GJRK_DEL_CGRK
      set @flagreturn = 1
   end
   else
   begin
      rollback transaction trans_GJRK_DEL_CGRK
      set @flagreturn = 0
   end





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG










CREATE PROCEDURE [STORE_INVOICE]  
                 (
                  @BILLID varchar(22)      ---单据编号   
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @REFERBILLTYPE int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @VENDORFLAG  int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @VENDORID varchar(15)               --明细存货编号
declare @REFERBILLID varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @REFERBILLITEMNO varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @INVOICENOW  NUMERIC(20,10)               --含税单价
declare @QUANTITY  NUMERIC(20,10)               --含税单价
declare @BATCHCODE varchar(30)                     --序列号
declare @BILLKIND  INTEGER
declare @INVOICETYPE  INTEGER
--//declare @BILLKIN D INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @STOREHSFS   INTEGER

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
set @BILLID   = ltrim(rtrim(@BILLID))

		SELECT @BILLKIND=BILLKIND FROM     INVOICEM   where rtrim(BILLID) = @BILLID 
		SELECT @INVOICETYPE=INVOICETYPE FROM     INVOICEM   where rtrim(BILLID) = @BILLID 
    declare SM_Consign_INVOICE Cursor for Select  REFERBILLID,INVOICENOW,ITEMNO,REFERBILLTYPE   from INVOICED   where rtrim(BILLID) = @BILLID 

    Open SM_Consign_INVOICE

    fetch SM_Consign_INVOICE into @REFERBILLID,@INVOICENOW,@ITEMNO,@REFERBILLTYPE

    while @@fetch_status = 0            ----开始
    begin
	           IF  @REFERBILLTYPE=1
		BEGIN
		          UPDATE   STORECGRKM  set    INVOICEAMT=ISNULL(INVOICEAMT,0) +@INVOICENOW,INVOICETYPE=@INVOICETYPE
             		           WHERE  rtrim(BILLID) = @REFERBILLID
		END

	           IF  @REFERBILLTYPE=2 
		BEGIN
		          UPDATE   STOREXSCKM  set    INVOICEAMT=ISNULL(INVOICEAMT,0) +@INVOICENOW,INVOICETYPE=@INVOICETYPE
             		           WHERE  rtrim(BILLID) = @REFERBILLID
		END



	           IF  @REFERBILLTYPE=7
		BEGIN
		          UPDATE   STORECGTHM  set    INVOICEAMT=ISNULL(INVOICEAMT,0) +@INVOICENOW,INVOICETYPE=@INVOICETYPE
             		           WHERE  rtrim(BILLID) = @REFERBILLID
		END

	           IF  @REFERBILLTYPE=12 
		BEGIN
		          UPDATE   STOREXSTHM  set    INVOICEAMT=ISNULL(INVOICEAMT,0) +@INVOICENOW,INVOICETYPE=@INVOICETYPE
             		           WHERE  rtrim(BILLID) = @REFERBILLID
		END



    fetch SM_Consign_INVOICE into @REFERBILLID,@INVOICENOW,@ITEMNO,@REFERBILLTYPE

    END           ------- SM_Consign_INVOICE  WHILE

    close SM_Consign_INVOICE
    deallocate SM_Consign_INVOICE







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG










CREATE PROCEDURE [STORE_INVOICE_DEL]  
                 (
                  @BILLID varchar(22)      ---单据编号   
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @REFERBILLTYPE int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @VENDORFLAG  int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @VENDORID varchar(15)               --明细存货编号
declare @REFERBILLID varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @REFERBILLITEMNO varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @INVOICENOW  NUMERIC(20,10)               --含税单价
declare @QUANTITY  NUMERIC(20,10)               --含税单价
declare @BATCHCODE varchar(30)                     --序列号
declare @BILLKIND  INTEGER
--//declare @BILLKIN D INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @STOREHSFS   INTEGER

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
set @BILLID   = ltrim(rtrim(@BILLID))

		SELECT @BILLKIND=BILLKIND FROM     INVOICEM   where rtrim(BILLID) = @BILLID 
    declare SM_Consign_INVOICE_DEL Cursor for Select  REFERBILLID,INVOICENOW,ITEMNO,REFERBILLTYPE   from INVOICED   where rtrim(BILLID) = @BILLID 

    Open SM_Consign_INVOICE_DEL

    fetch SM_Consign_INVOICE_DEL into @REFERBILLID,@INVOICENOW,@ITEMNO,@REFERBILLTYPE

    while @@fetch_status = 0            ----开始
    begin
	           IF  @REFERBILLTYPE=1 
		BEGIN
		          UPDATE   STORECGRKM  set    INVOICEAMT=ISNULL(INVOICEAMT,0) -@INVOICENOW
             		           WHERE  rtrim(BILLID) = @REFERBILLID
		          UPDATE   STORECGRKM  set    INVOICETYPE=0
             		           WHERE  rtrim(BILLID) = @REFERBILLID  AND INVOICEAMT=0
			
		END

	           IF  @REFERBILLTYPE=2 
		BEGIN
		          UPDATE   STOREXSCKM  set    INVOICEAMT=ISNULL(INVOICEAMT,0) -@INVOICENOW
             		           WHERE  rtrim(BILLID) = @REFERBILLID
		          UPDATE   STOREXSCKM  set    INVOICETYPE=0
             		           WHERE  rtrim(BILLID) = @REFERBILLID  AND INVOICEAMT=0
		END



	           IF  @REFERBILLTYPE=7 
		BEGIN
		          UPDATE   STORECGTHM  set    INVOICEAMT=ISNULL(INVOICEAMT,0) -@INVOICENOW
             		           WHERE  rtrim(BILLID) = @REFERBILLID
		          UPDATE   STORECGTHM  set    INVOICETYPE=0
             		           WHERE  rtrim(BILLID) = @REFERBILLID  AND INVOICEAMT=0
			
		END

	           IF  @REFERBILLTYPE=12 
		BEGIN
		          UPDATE   STOREXSTHM  set    INVOICEAMT=ISNULL(INVOICEAMT,0) -@INVOICENOW
             		           WHERE  rtrim(BILLID) = @REFERBILLID
		          UPDATE   STOREXSTHM  set    INVOICETYPE=0
             		           WHERE  rtrim(BILLID) = @REFERBILLID  AND INVOICEAMT=0
		END



--------------------
    fetch SM_Consign_INVOICE_DEL into @REFERBILLID,@INVOICENOW,@ITEMNO,@REFERBILLTYPE

    END           ------- SM_Consign_INVOICE_DEL  WHILE

    close SM_Consign_INVOICE_DEL
    deallocate SM_Consign_INVOICE_DEL







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG



















CREATE PROCEDURE [STORE_JGD]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---是否现款标志
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @VENDORID   varchar(15)               --明细存货编号
declare @bankID   varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @RATE NUMERIC(20,10)                          --单据总金额
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @SUMAMT NUMERIC(20,10)                          --单据总金额
declare @UNITQTY NUMERIC(20,10)                          --单据总金额
declare @refqty NUMERIC(20,10)                          --引用数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @PRICETYPE INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

     set @BillDate =   (select BillDate  from STOREJGDM where rtrim(BILLID) = @BILLID)
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     

    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END

if  (select isnull(flagPost,0) from STOREJGDM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_JGD   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREJGDM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREJGDM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREJGDM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREJGDM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREJGDM where rtrim(BILLID) = @BILLID)
     set @VENDORID =   (select  VENDORID  from STOREJGDM where rtrim(BILLID) = @BILLID)
     set @BANKID =   (select BANKID  from STOREJGDM where rtrim(BILLID) = @BILLID)   ---------付款银行


    declare SM_Consign_JGD Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(unitPRICE,0) as PRICE, 
                                                                  DetailBillFlowID,UNITQTY,PRICETYPE    from STOREJGDD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_JGD

    fetch SM_Consign_JGD into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE, @DetailBillFlowID,@UNITQTY ,@PRICETYPE

    while @@fetch_status = 0            ----开始
    begin

-------缺少检测仓库  明日解决

                                      IF NOT (exists (select * from STORE where STOREID=@STOREID))
                                     BEGIN
			      rollback transaction trans_JGD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close SM_Consign_JGD
			    deallocate SM_Consign_JGD
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@STOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_JGD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_JGD
			    deallocate SM_Consign_JGD
                                          RETURN
			END




            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)*0.001  from GOODS where  GOODSID = @GOODSID)

---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	

	IF @PRICETYPE=0  
	BEGIN
		IF   @QTY<>0
		BEGIN
		SET  @PRICE=(@UNITQTY*@PRICE)/@QTY
		END

	END

	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE   ,@DetailBillFlowID  , @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     isnull(@REFQTY,0),0 )    
	          UPDATE   STOREJGDD  set    DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_JGD


-----------====================2012-09-04 begin

	IF   @INF_COSTINGTYPEID=6 
	Begin

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,2,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     isnull(@REFQTY,0),0 )    

-----///===	update DetailBillFlow  where ID=@NEWID
	END
-----------====================2012-09-04 end

--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END


--------------------
    fetch SM_Consign_JGD into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE, @DetailBillFlowID,@UNITQTY ,@PRICETYPE

    END           ------- SM_Consign_JGD  WHILE

    close SM_Consign_JGD
    deallocate SM_Consign_JGD

   update  STOREJGDM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
   update  STOREJGDD  set   AMT  =  Round(ISNULL(quantity,0)*ISNULL(UNITprice,0),2)               where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STOREJGDD  set   AMT  =  Round(ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)   where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0
    

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_JGD
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_JGD
      set @flagreturn = 0
   end
end















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_JGD_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @billtype   INT
declare @SFLAG   INT
declare @INF_COSTINGTYPEID  INT                ---本期期初加权价
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE from STOREJGDM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREJGDM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_JGD_DEL   --事物开始

	     set @BillType =   (select BillType  from STOREJGDM where rtrim(BILLID) = @BILLID)

    declare SM_Consign_JGD_DEL Cursor for Select GOODSID,DetailBillFlowID,STOREID,BILLID    from STOREJGDD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_JGD_DEL

    fetch SM_Consign_JGD_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@BILLID

    while @@fetch_status = 0            ----开始
    begin
                             DELETE   DetailBillFlow     WHERE  ID=@DetailBillFlowID
--------------------------------------以上是删除一条单据明细
       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END


		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@STOREID AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
    fetch SM_Consign_JGD_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@BILLID

    END           ------- SM_Consign_JGD_DEL  WHILE

    close SM_Consign_JGD_DEL
    deallocate SM_Consign_JGD_DEL

                             DELETE   DetailBillFlow     WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 AND BILLTYPE=@billtype
--------------------------------------以上上全部删除单据  是解决多次记帐失败的问题

   update  STOREJGDM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_JGD_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_JGD_DEL
      set @flagreturn = 0
   end
end







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG

























----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_LIUH]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ClientFlag int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ITEMNO varchar(15)               --明细存货编号
declare @YunShuDWID varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号、
declare @CLIENTID varchar(15)               --明细存货编号、
declare @VENDORID varchar(15)               --明细存货编号、
declare @INStoreID varchar(15)               --明细存货编号、
declare @SUMAMT  NUMERIC(20,10)               --明细存货编号、
declare @RATE  NUMERIC(20,10)               --明细存货编号、
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @STOREIDEqty NUMERIC(20,10)                          --仓库数量
declare @REFqty NUMERIC(20,10)                          --数量
declare @UNITqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @PRICETYPE  NUMERIC(20,10)               --含税单价
declare @KEYONGQTY  NUMERIC(20,10)               --含税单价
declare @TAXRATE NUMERIC(20,10)               --含税单价
declare @APRICE  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID  varchar(50)
declare @GOODSNAME varchar(30)                     --序列号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @REITEMNO VARCHAR(25)
declare @BILLDATE DATEtime
declare @SFLAG  INTEGER
declare @YYYYMM_FLAG  INTEGER
declare @count  INTEGER
declare @MaxRate  NUMERIC(20,10)               --含税单价
declare @MinRate  NUMERIC(20,10)               --含税单价
declare @DMinSPrice NUMERIC(20,10)               --含税单价

declare @STOREHSFS   INTEGER
declare @ZhongLiangXZ   INTEGER
declare @XSPriceXZ   INTEGER
declare @NEGCLOSEOFF   bit
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
       SELECT    @NEGCLOSEOFF=(SELECT  NEGCLOSEOFF  FROM   ACCINFO    WHERE   GUID='0001' )           

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )  
         


set @BILLID   = ltrim(rtrim(@BILLID))
SET  @RETURNSTRING='  '
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @ZhongLiangXZ   = (select optionvalue from accoptions where optionname ='ZhongLiangXZ')     
     set @XSPriceXZ   = (select optionvalue from accoptions where optionname ='XSPriceXZ')     

     set @BillDate =   (select BillDate  from STORELIUHM where rtrim(BILLID) = @BILLID)

    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 


      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END


if  (select isnull(flagPost,0) from STORELIUHM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_LIUH   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STORELIUHM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STORELIUHM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STORELIUHM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STORELIUHM where rtrim(BILLID) = @BILLID)
     set @CLIENTID =   (select CLIENTID  from STORELIUHM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STORELIUHM where rtrim(BILLID) = @BILLID)
     set @ClientFLAG =   (select  ISNULL(ClientFLAG,1)   from STORELIUHM where rtrim(BILLID) = @BILLID)
     set @INStoreID =   (select BuMenID  from  STORELIUHM where rtrim(BILLID) = @BILLID)   ---------收款银行


   	 SELECT @SUMAMT= (SELECT SUM(ROUND(DISC*0.01*unitprice*UNITQTY*(1+ISNULL(TAXRATE,0)*0.01),2)) FROM   STORELIUHD  where rtrim(BILLID) = @BILLID)
   	 SELECT @SUMAMT=0


                                      IF NOT (exists (select * from ViewCLIENT where CLIENTID=@CLIENTID   and CLIENTFLAG=@CLIENTFLAG))
                                     BEGIN
			      rollback transaction  trans_LIUH 
			      set @flagreturn = 0
                                              SET @RETURNSTRING='客户不能为空或客户不存在，单据不能记帐'
                                          RETURN
			END




    declare SM_Consign_STORELIUHM Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(UNITPRICE,0)*ISNULL(DISC,0)*0.01 as PRICE, 
                                                                   REDetailBillFlowID,ISNULL(UNITQTY,0) AS UNITQTY  ,PRICETYPE,TAXRATE  from STORELIUHD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_STORELIUHM

    fetch SM_Consign_STORELIUHM into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY,@PRICETYPE,@TAXRATE 

    while @@fetch_status = 0            ----开始
    begin


            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)*0.001  from GOODS where  GOODSID = @GOODSID)


---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	


	IF @PRICETYPE=1   
	BEGIN
   	 SELECT @SUMAMT=@SUMAMT+ROUND(@price*@QTY*(1+ISNULL(@TAXRATE,0)*0.01),2)
	END
	IF @PRICETYPE=0  
	BEGIN
   	 SELECT @SUMAMT=@SUMAMT+ROUND(@price*@UNITQTY*(1+ISNULL(@TAXRATE,0)*0.01),2)

		IF   @QTY<>0
		BEGIN
		SET  @PRICE=(@UNITQTY*@PRICE)/@QTY
		END

	END



------------------------------------------

                                        IF NOT (exists (select * from STORE where STOREID=@STOREID))
                                     BEGIN
			      rollback transaction trans_LIUH
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close  SM_Consign_STORELIUHM
			    deallocate  SM_Consign_STORELIUHM
                                          RETURN
			END
--------------------------------------------
------------更改为数量库存报警
                        IF    @NEGCLOSEOFF=0 
			BEGIN 
--	                             	 EXEC   GETGOODSIDEQTY  @STOREID,@GOODSID,@YYYYMM,@EQTY=@STOREIDEQTY   OUTPUT
	                             	 EXEC   GETGOODSIDMEQTY  @STOREID,@GOODSID,@YYYYMM,@MEQTY=@STOREIDEQTY   OUTPUT

	                                        IF @UNITQTY >  ISNULL(@STOREIDEQTY,0)
             		                        BEGIN
                          		                  SET  @GOODSNAME =(SELECT NAME  FROM GOODS WHERE GOODSID=@GOODSID)
				      rollback transaction trans_LIUH
				      set @flagreturn = 0
             		                                 SET @RETURNSTRING='此'+@GOODSNAME+'库存不足不能记帐'
				    close  SM_Consign_STORELIUHM
				    deallocate  SM_Consign_STORELIUHM
	                                          RETURN
				END
			END

--------------------------------------------

            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)

	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE ,@REDetailBillFlowID,  @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',-1,@QTY*@PRICE,null,
	     0,0   )    
--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

                      select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID         -----------反填的是吨价格
	          UPDATE     STORELIUHD     set    APRICE=@APRICE,  DetailBillFlowID=@NEWID
           		           WHERE CURRENT OF  SM_Consign_STORELIUHM


-------------------------------以上解决出库-----以下解决入库

	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE ,@REDetailBillFlowID,  @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@INStoreID,'F',1,@QTY*@PRICE,null,
	     0,0   )    




--------------------------------------------------------------------------
    fetch SM_Consign_STORELIUHM into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY,@PRICETYPE,@TAXRATE 


    END           ------- SM_Consign_STORELIUHM  WHILE

    close SM_Consign_STORELIUHM
    deallocate SM_Consign_STORELIUHM

-------------------





   update  STORELIUHM  set  flagPost = 1,YYYYMM =@BILLYYYYMM   ,SUMAMT=VendorHKSum ,INVOICEAMT=0          where ltrim(rtrim(BILLID)) = @BILLID 
   update  STORELIUHD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)          where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STORELIUHD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)   where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_LIUH
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_LIUH
      set @flagreturn = 0
   end
end













----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG





















----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_LIUH_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare  @INF_COSTINGTYPEID  INT
declare  @ClientFlag  INT
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @CLIENTID varchar(10)                   --单句会计年月     
declare @VENDORID varchar(10)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @ChaCheSID VARCHAR(25)
declare @INSTOREID    varchar(15)               --明细存货编号

declare @STOREID    varchar(15)               --明细存货编号
declare @REDetailBillFlowID   varchar(30)                     --序列号
declare @REITEMNO   varchar(30)                     --序列号
declare @QUANTITY   NUMERIC(20,10)                     --序列号
declare @UNITQTY   NUMERIC(20,10)                     --序列号
declare @BILLTYPE   INTEGER
declare @SFLAG   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

                                              SET @RETURNSTRING='   '


	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STORELIUHM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STORELIUHM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_LIUH_DEL   --事物开始

     set @BillType =   (select BillType  from STORELIUHM where rtrim(BILLID) = @BILLID)
     set @INStoreID =   (select BuMenID  from  STORELIUHM where rtrim(BILLID) = @BILLID)   ---------收款银行

		DELETE    DetailBillFlow    WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@billTYPE

		DELETE    DetailBillFlow    WHERE  ltrim(rtrim(BILLID)) = '00'+Substring(@BILLID,3,6)  AND YYYYMMBILL=1
							  AND  BILLTYPE=@billTYPE
------------------------------------以上是删除全部单据明细

    declare SM_Consign_LIUH_DEL Cursor for Select GOODSID,DetailBillFlowID,STOREID,REDetailBillFlowID ,QUANTITY,UNITQTY   from STORELIUHD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_LIUH_DEL

    fetch SM_Consign_LIUH_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@REDetailBillFlowID,@QUANTITY,@UNITQTY

    while @@fetch_status = 0            ----开始
    begin
       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID

                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                             execute      APRICECACULATOR_STORE   @GOODSID,@INSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
	                             execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
	                             execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@INSTOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@INSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
             		                execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
             		                execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@INSTOREID,@YYYYMM
				     END
                            END






     update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@STOREID AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
    fetch SM_Consign_LIUH_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@REDetailBillFlowID,@QUANTITY,@UNITQTY

    END           ------- SM_Consign_LIUH_DEL  WHILE

    close SM_Consign_LIUH_DEL
    deallocate SM_Consign_LIUH_DEL








   update  STORELIUHM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_LIUH_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_LIUH_DEL
      set @flagreturn = 0
   end
end












----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














--------------------------------------------------------------------

CREATE PROCEDURE [STORE_MOVE]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。


declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)

declare @bill_type int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @BANKID varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @CLIENTID   varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @SUMAMT NUMERIC(20,10)                          --数量
declare @refqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @INBANKID VARCHAR(25)
declare @BILLDATE DATEtime
declare @MINBILLDATE DATEtime
declare @MAXBILLDATE DATEtime
declare @B_CODE VARCHAR(25)
declare @V_DATE DATEtime
declare @B_ID INTEGER
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))


     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @BillDate =   (select BillDate  from STOREMOVEM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END



if  (select isnull(flagPost,0) from STOREMOVEM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_MOVE   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREMOVEM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREMOVEM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREMOVEM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREMOVEM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  SFLAG  from STOREMOVEM where rtrim(BILLID) = @BILLID)
     set @INBANKID =   (select  VENDORID  from STOREMOVEM where rtrim(BILLID) = @BILLID)     ----实际上是出
     set @BANKID =   (select  BUMENID  from STOREMOVEM where rtrim(BILLID) = @BILLID)


                                      IF NOT (exists (select * from BANK where BANKID=@BANKID))
                                     BEGIN
			      rollback transaction trans_MOVE
			      set @flagreturn = 0
                                              SET @RETURNSTRING='银行科目不能为空或银行科目不存在，单据不能记帐'
                                          RETURN
			END

                                      IF @INBANKID=@BANKID
                                     BEGIN
			      rollback transaction trans_MOVE
			      set @flagreturn = 0
                                              SET @RETURNSTRING='银行科目不能相同，单据不能记帐'
                                          RETURN
			END
   	 SELECT @SUMAMT= (SELECT isnull(DISCAMT,0)  FROM  STOREMOVEM   where rtrim(BILLID) = @BILLID)

                                      IF @SUMAMT=0
                                     BEGIN
			      rollback transaction trans_MOVE
			      set @flagreturn = 0
                                              SET @RETURNSTRING='金额不能为0，单据不能记帐'
                                          RETURN
			END

------------------------------以下是解决科目帐的算法
            IF   (not exists(select *  from BANKBILLFLOW  where 
             		                                    (rtrim(BANKID) = @INBANKID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@INBANKID,
		     0,0,Null,
		     @inoutFlag,0  )    
            END      ------IF   END
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@INBANKID,
		     0,@SUMAMT,Null,
		     -1,0  )    
                            execute      BANK_CACULATOR_YYYYMM   @INBANKID,@YYYYMM
------------------------------------
            IF   (not exists(select *  from BANKBILLFLOW  where 
             		                                    (rtrim(BANKID) = @BANKID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,0,Null,
		     @inoutFlag,0  )    
            END      ------IF   END
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,@SUMAMT,Null,
		     1,0  )    
                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM

   update  STOREMOVEM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_MOVE
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_MOVE
      set @flagreturn = 0
   end
end






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_MOVE_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @BANKID    varchar(15)               --明细存货编号
declare @INBANKID    varchar(15)               --明细存货编号
declare @CLIENTID   varchar(30)                     --序列号
declare @INF_COSTINGTYPEID   INT
declare @REFQTY   NUMERIC(20,10)
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STOREMOVEM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREMOVEM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_MOVE_DEL   --事物开始


	     set @INBANKID =   (select  VENDORID  from STOREMOVEM where rtrim(BILLID) = @BILLID)



		DELETE   BANKBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=11

                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM
                            execute      BANK_CACULATOR_YYYYMM   @INBANKID,@YYYYMM


   update  STOREMOVEM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_MOVE_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_MOVE_DEL
      set @flagreturn = 0
   end
end






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG























----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_QGAD]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @MStoreID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号、
declare @CLIENTID varchar(15)               --明细存货编号、
declare @SUMAMT  NUMERIC(20,10)               --明细存货编号、
declare @goodsid varchar(15)               --明细存货编号
declare @Mgoodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @STOREIDEqty NUMERIC(20,10)                          --仓库数量
declare @REFqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @RATE  NUMERIC(20,10)               --含税单价
declare @APRICE  NUMERIC(20,10)               --含税单价
declare @UNITQTY  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID  varchar(50)
declare @DetailBillFlowID  varchar(50)
declare @GOODSNAME varchar(30)                     --序列号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @SFLAG  INTEGER
declare @PRICETYPE  INTEGER
declare @YYYYMM_FLAG  INTEGER
declare @count  INTEGER
declare @STOREHSFS   INTEGER
declare @NEGCLOSEOFF   bit
declare @MaxRate  NUMERIC(20,10)               --含税单价
declare @MinRate  NUMERIC(20,10)               --含税单价
declare @DMinSPrice NUMERIC(20,10)               --含税单价
declare @ZhongLiangXZ   INTEGER
declare @XSPriceXZ   INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @NEGCLOSEOFF=(SELECT  NEGCLOSEOFF  FROM   ACCINFO    WHERE   GUID='0001' )           

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           


set @BILLID   = ltrim(rtrim(@BILLID))
SET  @RETURNSTRING='  '
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @ZhongLiangXZ   = (select optionvalue from accoptions where optionname ='ZhongLiangXZ')     
     set @XSPriceXZ   = (select optionvalue from accoptions where optionname ='XSPriceXZ')     

     set @BillDate =   (select BillDate  from STOREQGADM where rtrim(BILLID) = @BILLID)
    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 


      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END


if  (select isnull(flagPost,0) from STOREQGADM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_QGAD   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREQGADM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREQGADM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREQGADM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREQGADM where rtrim(BILLID) = @BILLID)
     set @CLIENTID =   (select CLIENTID  from STOREQGADM where rtrim(BILLID) = @BILLID)
     set @MStoreID =   (select StoreID  from STOREQGADM where rtrim(BILLID) = @BILLID)
     set @MGOODSID =   (select GOODSID  from STOREQGADM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREQGADM where rtrim(BILLID) = @BILLID)



                                        IF NOT (exists (select * from GOODS where GOODSID=@MGOODSID))
                                     BEGIN
			      rollback transaction trans_QGAD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='加工的成品件不能为空，单据不能记帐'
                                          RETURN
			END

                                        IF NOT (exists (select * from STORE where STOREID=@MStoreID))
                                     BEGIN
			      rollback transaction trans_QGAD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库不能为空或仓库不存在，单据不能记帐'
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@MStoreID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_QGAD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
                                          RETURN
			END
	    select  @UNITQTY = (select SumQTY  from STOREQGADM where rtrim(BILLID) = @BILLID)


			declare @FuKuCunOUTQty int    ---1代表数量提示，0代表重量提示
			declare @BiJiaoQTY  NUMERIC(20,10)  ---比较过度用的变量


		        set @FuKuCunOUTQty  = (select optionvalue from accoptions where optionname ='FuKuCunOUTQty')     
		
                        IF    @NEGCLOSEOFF=0 
			BEGIN 
				IF @FuKuCunOUTQty=1
				BEGIN 
	                             	EXEC   GETGOODSIDMEQTY  @MSTOREID,@MGOODSID,@YYYYMM,@MEQTY=@STOREIDEQTY   OUTPUT
					SET @BiJiaoQTY=@UNITQTY
				END
				ELSE
				BEGIN 
	                             	EXEC   GETGOODSIDEQTY  @MSTOREID,@MGOODSID,@YYYYMM,@EQTY=@STOREIDEQTY   OUTPUT				
					select  @BiJiaoQTY = (select INVOICEAMT  from STOREQGADM where rtrim(BILLID) = @BILLID)
----					SET @BiJiaoQTY=@QTY
				END
                                IF @BiJiaoQTY >  ISNULL(@STOREIDEQTY,0)
             		                        BEGIN
                          		                  SET  @GOODSNAME =(SELECT NAME  FROM GOODS WHERE GOODSID=@MGOODSID)
				      rollback transaction trans_QGAD
				      set @flagreturn = 0
             		                                 SET @RETURNSTRING='此'+@GOODSNAME+'库存不足不能记帐'
	                                          RETURN
				END
			END



    declare SM_Consign_QGAD Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(unitPRICE,0) as PRICE, 
                                                                  REDetailBillFlowID,UNITQTY,PRICETYPE    from STOREQGADD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_QGAD

    fetch SM_Consign_QGAD into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY,@PRICETYPE
    while @@fetch_status = 0            ----开始
    begin
                                        IF NOT (exists (select * from STORE where STOREID=@STOREID))
                                     BEGIN
			      rollback transaction trans_QGAD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库不能为空或仓库不存在，单据不能记帐'
			    close  SM_Consign_QGAD
			    deallocate  SM_Consign_QGAD
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@STOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_QGAD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_QGAD
			    deallocate SM_Consign_QGAD
                                          RETURN
			END




            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)*0.001  from GOODS where  GOODSID = @GOODSID)

---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	

	IF @PRICETYPE=0  
	BEGIN
		IF   @QTY<>0
		BEGIN
		SET  @PRICE=(@UNITQTY*@PRICE)/@QTY
		END

	END

	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE   ,@DetailBillFlowID  , @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     isnull(@REFQTY,0),0 )    
	          UPDATE   STOREQTRKD  set    DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_QTRK


-----------====================2012-09-04 begin

	IF   @INF_COSTINGTYPEID=6 
	Begin

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,2,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     isnull(@REFQTY,0),0 )    

-----///===	update DetailBillFlow  where ID=@NEWID
	END
-----------====================2012-09-04 end

--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

--------------------
    fetch SM_Consign_QGAD into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY,@PRICETYPE

    END           ------- SM_Consign_QGAD  WHILE

    close SM_Consign_QGAD
    deallocate SM_Consign_QGAD

--------------------------------
-----------------------------以下是入库部分

	    set @GOODSID=@MGOODSID
	    set @StoreID =   (select StoreID  from STOREQGADM where rtrim(BILLID) = @BILLID)
	    select  @QTY = (select INVOICEAMT  from STOREQGADM where rtrim(BILLID) = @BILLID)
	    select  @PRICE = (select SumAMT  from STOREQGADM where rtrim(BILLID) = @BILLID)
	    select  @UNITQTY = (select SumQTY  from STOREQGADM where rtrim(BILLID) = @BILLID)
	    select  @PRICETYPE = (select PRICETYPE  from STOREQGADM where rtrim(BILLID) = @BILLID)

            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)*0.001  from GOODS where  GOODSID = @GOODSID)

---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	

	IF @PRICETYPE=0  
	BEGIN
		IF   @QTY<>0
		BEGIN
		SET  @PRICE=(@UNITQTY*@PRICE)/@QTY
		END

	END

	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE   ,@DetailBillFlowID  , @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',-1,@QTY*@PRICE,null, 
	     isnull(@REFQTY,0),0 )    
/*	          UPDATE   STOREQGADD  set    DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_QGAD
*/

--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END







   update  STOREQGADM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
   update  STOREQGADD  set   AMT  =  Round(ISNULL(quantity,0)*ISNULL(UNITprice,0),2)               where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STOREQGADD  set   AMT  =  Round(ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)            where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_QGAD
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_QGAD
      set @flagreturn = 0
   end
end















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG







----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_QGAD_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare  @INF_COSTINGTYPEID  INT
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @CLIENTID varchar(10)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @REDetailBillFlowID   varchar(30)                     --序列号
declare @QUANTITY   NUMERIC(20,10)                     --序列号
declare @BILLTYPE   INTEGER
declare @SFLAG   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

                                              SET @RETURNSTRING='   '


	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @YYYYMMBILL =   (select YYYYMM  from STOREQGADM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREQGADM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_QGAD_DEL   --事物开始

     set @BillType =   (select BillType  from STOREQGADM where rtrim(BILLID) = @BILLID)


    declare SM_Consign_QGAD_DEL Cursor for Select GOODSID,DetailBillFlowID,STOREID,REDetailBillFlowID ,QUANTITY  from STOREQGADD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_QGAD_DEL

    fetch SM_Consign_QGAD_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@REDetailBillFlowID,@QUANTITY

    while @@fetch_status = 0            ----开始
    begin

                             DELETE   DetailBillFlow   WHERE  ID=@DetailBillFlowID
       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@STOREID AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
    fetch SM_Consign_QGAD_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@REDetailBillFlowID,@QUANTITY

    END           ------- SM_Consign_QGAD_DEL  WHILE

    close SM_Consign_QGAD_DEL
    deallocate SM_Consign_QGAD_DEL

		DELETE    DetailBillFlow    WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND (YYYYMMBILL in (1,2))
							  AND  BILLTYPE=@billTYPE
------------------------------------以上是删除全部单据明细
     set @StoreID =   (select StoreID  from STOREQGADM where rtrim(BILLID) = @BILLID)
     set @GoodsID =   (select GoodsID  from STOREQGADM where rtrim(BILLID) = @BILLID)
       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END






   update  STOREQGADM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_QGAD_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_QGAD_DEL
      set @flagreturn = 0
   end
end











----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG

































----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_QGD]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @MStoreID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号、
declare @CLIENTID varchar(15)               --明细存货编号、
declare @SUMAMT  NUMERIC(20,10)               --明细存货编号、
declare @goodsid varchar(15)               --明细存货编号
declare @Mgoodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @STOREIDEqty NUMERIC(20,10)                          --仓库数量
declare @REFqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @RATE  NUMERIC(20,10)               --含税单价
declare @APRICE  NUMERIC(20,10)               --含税单价
declare @UNITQTY  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID  varchar(50)
declare @DetailBillFlowID  varchar(50)
declare @GOODSNAME varchar(30)                     --序列号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @SFLAG  INTEGER
declare @PRICETYPE  INTEGER
declare @YYYYMM_FLAG  INTEGER
declare @count  INTEGER
declare @STOREHSFS   INTEGER
declare @NEGCLOSEOFF   bit
declare @MaxRate  NUMERIC(20,10)               --含税单价
declare @MinRate  NUMERIC(20,10)               --含税单价
declare @DMinSPrice NUMERIC(20,10)               --含税单价
declare @ZhongLiangXZ   INTEGER
declare @XSPriceXZ   INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @NEGCLOSEOFF=(SELECT  NEGCLOSEOFF  FROM   ACCINFO    WHERE   GUID='0001' )           

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           


set @BILLID   = ltrim(rtrim(@BILLID))
SET  @RETURNSTRING='  '
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @ZhongLiangXZ   = (select optionvalue from accoptions where optionname ='ZhongLiangXZ')     
     set @XSPriceXZ   = (select optionvalue from accoptions where optionname ='XSPriceXZ')     

     set @BillDate =   (select BillDate  from STOREQGDM where rtrim(BILLID) = @BILLID)
    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END


if  (select isnull(flagPost,0) from STOREQGDM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_QGD   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @CLIENTID =   (select CLIENTID  from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @MStoreID =   (select VendorID  from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @MGOODSID =   (select GOODSID  from STOREQGDM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREQGDM where rtrim(BILLID) = @BILLID)




                                        IF NOT (exists (select * from STORE where STOREID=@MStoreID))
                                     BEGIN
			      rollback transaction trans_QGD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库不能为空或仓库不存在，单据不能记帐'
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@MStoreID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_QGD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
                                          RETURN
			END



    declare SM_Consign_QGD_IN Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(PRICE,0) as PRICE, 
                                                                  REDetailBillFlowID,UNITQTY,PRICETYPE    from STOREQGDS where rtrim(BILLID) = @BILLID 

    Open SM_Consign_QGD_IN

    fetch SM_Consign_QGD_IN into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY,@PRICETYPE
    while @@fetch_status = 0            ----开始
    begin

                                        IF NOT (exists (select * from STORE where STOREID=@STOREID))
                                     BEGIN
			      rollback transaction trans_QGD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库不能为空或仓库不存在，单据不能记帐'
			    close  SM_Consign_QGD_IN
			    deallocate  SM_Consign_QGD_IN
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@STOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_QGD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_QGD_IN
			    deallocate SM_Consign_QGD_IN
                                          RETURN
			END




			declare @FuKuCunOUTQty int    ---1代表数量提示，0代表重量提示
			declare @BiJiaoQTY  NUMERIC(20,10)  ---比较过度用的变量


		        set @FuKuCunOUTQty  = (select optionvalue from accoptions where optionname ='FuKuCunOUTQty')     
		
                        IF    @NEGCLOSEOFF=0 
			BEGIN 
				IF @FuKuCunOUTQty=1
				BEGIN 
	                             	EXEC   GETGOODSIDMEQTY  @STOREID,@GOODSID,@YYYYMM,@MEQTY=@STOREIDEQTY   OUTPUT
					SET @BiJiaoQTY=@UNITQTY
				END
				ELSE
				BEGIN 
	                             	EXEC   GETGOODSIDEQTY  @STOREID,@GOODSID,@YYYYMM,@EQTY=@STOREIDEQTY   OUTPUT				
					SET @BiJiaoQTY=@QTY
				END
                                IF @BiJiaoQTY >  ISNULL(@STOREIDEQTY,0)
             		                        BEGIN
                          		                  SET  @GOODSNAME =(SELECT NAME  FROM GOODS WHERE GOODSID=@GOODSID)
				      rollback transaction trans_QGD
				      set @flagreturn = 0
             		                                 SET @RETURNSTRING='此'+@GOODSNAME+'库存不足不能记帐'
				    close  SM_Consign_QGD_IN
				    deallocate  SM_Consign_QGD_IN
	                                          RETURN
				END
			END

            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)*0.001  from GOODS where  GOODSID = @GOODSID)




---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	




	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE  ,@REDetailBillFlowID,  @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',-1,@QTY*@PRICE,null,
	     0,0   )    

--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

-------------------其实三种成本价的核算方式都一样                    
--------反填成本单价
		IF   @SFLAG=0   --------反填
		BEGIN
			IF @PRICETYPE=1    ----吨
			BEGIN
	                   	   select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID
			          UPDATE     STOREQGDD     set    APRICE=@APRICE,UNITPRICE=@APRICE,  DetailBillFlowID=@NEWID
             		    	       WHERE CURRENT OF  SM_Consign_QGD_IN
			END

			IF @PRICETYPE=0    ----数量
			BEGIN
		                      select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID
			          UPDATE     STOREQGDD     set    APRICE=@APRICE,UNITPRICE=@APRICE*@QTY/@UNITQTY,  DetailBillFlowID=@NEWID
	             		    	       WHERE CURRENT OF  SM_Consign_QGD_IN
			END

		END
		IF   @SFLAG=1   --------反填
		BEGIN
			          UPDATE     STOREQGDD     set      DetailBillFlowID=@NEWID
             			           WHERE CURRENT OF  SM_Consign_QGD_IN
		END

--------------------
    fetch SM_Consign_QGD_IN into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY,@PRICETYPE

    END           ------- SM_Consign_QGD_IN  WHILE

    close SM_Consign_QGD_IN
    deallocate SM_Consign_QGD_IN

--------------------------------
-----------------------------以下是入库部分
	set @STOREID=@MStoreID


    declare SM_Consign_QGD_IN Cursor for Select  ITEMNO,GOODSID, isnull(QUANTITY,0) as qty,isnull(unitPRICE,0) as PRICE, 
                                                                  DetailBillFlowID,UNITQTY,PRICETYPE    from STOREQGDD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_QGD_IN

    fetch SM_Consign_QGD_IN into @ITEMNO,@GOODSID,@qty,@PRICE, @DetailBillFlowID,@UNITQTY ,@PRICETYPE

    while @@fetch_status = 0            ----开始
    begin

-------缺少检测仓库  明日解决



            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)*0.001  from GOODS where  GOODSID = @GOODSID)

---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	

	IF @PRICETYPE=0  
	BEGIN
		IF   @QTY<>0
		BEGIN
		SET  @PRICE=(@UNITQTY*@PRICE)/@QTY
		END

	END

	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE   ,@DetailBillFlowID  , @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     isnull(@REFQTY,0),0 )    
	          UPDATE   STOREQGDD  set    DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_QGD_IN


-----------====================2012-09-04 begin

	IF   @INF_COSTINGTYPEID=6 
	Begin

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,2,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     isnull(@REFQTY,0),0 )    

-----///===	update DetailBillFlow  where ID=@NEWID
	END
-----------====================2012-09-04 end

--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END


--------------------
    fetch SM_Consign_QGD_IN into @ITEMNO,@GOODSID,@qty,@PRICE, @DetailBillFlowID,@UNITQTY ,@PRICETYPE

    END           ------- SM_Consign_QGD_IN  WHILE

    close SM_Consign_QGD_IN
    deallocate SM_Consign_QGD_IN  


   update  STOREQGDM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
   update  STOREQGDD  set   AMT  =  Round(ISNULL(quantity,0)*ISNULL(UNITprice,0),2)               where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STOREQGDD  set   AMT  =  Round(ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)            where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_QGD
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_QGD
      set @flagreturn = 0
   end
end















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG


















----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_QGD_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare  @INF_COSTINGTYPEID  INT
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @CLIENTID varchar(10)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @REDetailBillFlowID   varchar(30)                     --序列号
declare @QUANTITY   NUMERIC(20,10)                     --序列号
declare @BILLTYPE   INTEGER
declare @SFLAG   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

                                              SET @RETURNSTRING='   '


	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STOREQGDM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREQGDM where ltrim(rtrim(BILLID)) = @BILLID ) = 0 
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_QGD_DEL   --事物开始

     set @BillType =   (select BillType  from STOREQGDM where rtrim(BILLID) = @BILLID)
		DELETE    DetailBillFlow    WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND (YYYYMMBILL in (1,2))
							  AND  BILLTYPE=@billTYPE


    declare SM_Consign_QGD_DEL Cursor for Select GOODSID,DetailBillFlowID,STOREID,REDetailBillFlowID ,QUANTITY  from STOREQGDS where rtrim(BILLID) = @BILLID 

    Open SM_Consign_QGD_DEL

    fetch SM_Consign_QGD_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@REDetailBillFlowID,@QUANTITY

    while @@fetch_status = 0            ----开始
    begin

       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

    update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@STOREID AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
    fetch SM_Consign_QGD_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@REDetailBillFlowID,@QUANTITY

    END           ------- SM_Consign_QGD_DEL  WHILE

    close SM_Consign_QGD_DEL
    deallocate SM_Consign_QGD_DEL

------------------------------------以上是删除全部单据明细
     set @StoreID =   (select VendorID  from STOREQGDM where rtrim(BILLID) = @BILLID)

    declare SM_Consign_QGD_IN_DEL Cursor for Select GOODSID,DetailBillFlowID,REDetailBillFlowID ,QUANTITY  from STOREQGDD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_QGD_IN_DEL

    fetch SM_Consign_QGD_IN_DEL into @GOODSID,@DetailBillFlowID,@REDetailBillFlowID,@QUANTITY

    while @@fetch_status = 0            ----开始
    begin

       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@STOREID AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
    fetch SM_Consign_QGD_IN_DEL into @GOODSID,@DetailBillFlowID,@REDetailBillFlowID,@QUANTITY

    END           ------- SM_Consign_QGD_IN_DEL  WHILE

    close SM_Consign_QGD_IN_DEL
    deallocate SM_Consign_QGD_IN_DEL



   update  STOREQGDM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_QGD_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_QGD_DEL
      set @flagreturn = 0
   end
end













----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG





























----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_QTCK]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号、
declare @CLIENTID varchar(15)               --明细存货编号、
declare @SUMAMT  NUMERIC(20,10)               --明细存货编号、
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @STOREIDEqty NUMERIC(20,10)                          --仓库数量
declare @REFqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @RATE  NUMERIC(20,10)               --含税单价
declare @APRICE  NUMERIC(20,10)               --含税单价
declare @UNITQTY  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID  varchar(50)
declare @GOODSNAME varchar(30)                     --序列号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @SFLAG  INTEGER
declare @PRICETYPE  INTEGER
declare @YYYYMM_FLAG  INTEGER
declare @count  INTEGER
declare @STOREHSFS   INTEGER
declare @NEGCLOSEOFF   bit
declare @MaxRate  NUMERIC(20,10)               --含税单价
declare @MinRate  NUMERIC(20,10)               --含税单价
declare @DMinSPrice NUMERIC(20,10)               --含税单价
declare @ZhongLiangXZ   INTEGER
declare @XSPriceXZ   INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @JianShu [int] 
declare @MeiJianQty [T_QUANTITY] 
declare @LingTou [T_QUANTITY] 

       SELECT    @NEGCLOSEOFF=(SELECT  NEGCLOSEOFF  FROM   ACCINFO    WHERE   GUID='0001' )           

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           


set @BILLID   = ltrim(rtrim(@BILLID))
SET  @RETURNSTRING='  '
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @ZhongLiangXZ   = (select optionvalue from accoptions where optionname ='ZhongLiangXZ')     
     set @XSPriceXZ   = (select optionvalue from accoptions where optionname ='XSPriceXZ')     

     set @BillDate =   (select BillDate  from STOREQTCKM where rtrim(BILLID) = @BILLID)

    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END


if  (select isnull(flagPost,0) from STOREQTCKM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_QTCK   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREQTCKM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREQTCKM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREQTCKM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREQTCKM where rtrim(BILLID) = @BILLID)
     set @CLIENTID =   (select CLIENTID  from STOREQTCKM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREQTCKM where rtrim(BILLID) = @BILLID)

    declare SM_Consign_QTCK Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(PRICE,0) as PRICE, 
                                                                  REDetailBillFlowID,UNITQTY,PRICETYPE,JianShu,MeiJianQty,LingTou    from STOREQTCKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_QTCK

    fetch SM_Consign_QTCK into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY,@PRICETYPE,@JianShu,@MeiJianQty,@LingTou
    while @@fetch_status = 0            ----开始
    begin
                     set @MeiJianQty =   (select ISNULL(RATE1,0)  from GOODS where  GOODSID = @GOODSID)


                            IF (ISNULL(@JianShu,0)*ISNULL(@MeiJianQty,0)+ISNULL(@LingTou,0)<>@Unitqty) AND (ISNULL(@JianShu,0)<>0 OR ISNULL(@LingTou,0)<>0)
                                     BEGIN
			      rollback transaction trans_QTCK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='件数*每件数量+零头与数量不等，单据不能记帐'
			    close  SM_Consign_QTCK
			    deallocate  SM_Consign_QTCK
                                          RETURN
			END

                                        IF NOT (exists (select * from STORE where STOREID=@STOREID))
                                     BEGIN
			      rollback transaction trans_QTCK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close  SM_Consign_QTCK
			    deallocate  SM_Consign_QTCK
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@STOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_QTCK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_QTCK
			    deallocate SM_Consign_QTCK
                                          RETURN
			END




			declare @FuKuCunOUTQty int    ---1代表数量提示，0代表重量提示
			declare @BiJiaoQTY  NUMERIC(20,10)  ---比较过度用的变量


		        set @FuKuCunOUTQty  = (select optionvalue from accoptions where optionname ='FuKuCunOUTQty')     
		
                        IF    @NEGCLOSEOFF=0 
			BEGIN 
				IF @FuKuCunOUTQty=1
				BEGIN 
	                             	EXEC   GETGOODSIDMEQTY  @STOREID,@GOODSID,@YYYYMM,@MEQTY=@STOREIDEQTY   OUTPUT
					SET @BiJiaoQTY=@UNITQTY
				END
				ELSE
				BEGIN 
	                             	EXEC   GETGOODSIDEQTY  @STOREID,@GOODSID,@YYYYMM,@EQTY=@STOREIDEQTY   OUTPUT				
					SET @BiJiaoQTY=@QTY
				END
                                IF @BiJiaoQTY >  ISNULL(@STOREIDEQTY,0)
          		        BEGIN
                          		                  SET  @GOODSNAME =(SELECT NAME  FROM GOODS WHERE GOODSID=@GOODSID)
				      rollback transaction trans_QTCK
				      set @flagreturn = 0
             		                                 SET @RETURNSTRING='此'+@GOODSNAME+'库存不足不能记帐'
				    close  SM_Consign_QTCK
				    deallocate  SM_Consign_QTCK
	                                          RETURN
				END
			END

            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)*0.001  from GOODS where  GOODSID = @GOODSID)




---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	




	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE  ,@REDetailBillFlowID,  @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',-1,@QTY*@PRICE,null,
	     0,0   )    

--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

-------------------其实三种成本价的核算方式都一样                    
--------反填成本单价
		IF   @SFLAG=0   --------反填
		BEGIN
			IF @PRICETYPE=1    ----吨
			BEGIN
	                   	   select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID
			          UPDATE     STOREQTCKD     set    APRICE=@APRICE,UNITPRICE=@APRICE,  DetailBillFlowID=@NEWID
             		    	       WHERE CURRENT OF  SM_Consign_QTCK
			END

			IF @PRICETYPE=0    ----数量
			BEGIN
		                      select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID
			          UPDATE     STOREQTCKD     set    APRICE=@APRICE,UNITPRICE=@APRICE*@QTY/@UNITQTY,  DetailBillFlowID=@NEWID
	             		    	       WHERE CURRENT OF  SM_Consign_QTCK
			END

		END
		IF   @SFLAG=1   --------反填
		BEGIN
			          UPDATE     STOREQTCKD     set      DetailBillFlowID=@NEWID
             			           WHERE CURRENT OF  SM_Consign_QTCK
		END

--------------------
    fetch SM_Consign_QTCK into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY,@PRICETYPE,@JianShu,@MeiJianQty,@LingTou

    END           ------- SM_Consign_QTCK  WHILE

    close SM_Consign_QTCK
    deallocate SM_Consign_QTCK


-------------------


   update  STOREQTCKM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
   update  STOREQTCKD  set   AMT  =  Round(ISNULL(quantity,0)*ISNULL(UNITprice,0),2)               where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STOREQTCKD  set   AMT  =  Round(ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)            where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_QTCK
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_QTCK
      set @flagreturn = 0
   end
end











----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_QTCK_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare  @INF_COSTINGTYPEID  INT
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @CLIENTID varchar(10)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @REDetailBillFlowID   varchar(30)                     --序列号
declare @QUANTITY   NUMERIC(20,10)                     --序列号
declare @BILLTYPE   INTEGER
declare @SFLAG   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间


       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

                                              SET @RETURNSTRING='   '


	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STOREQTCKM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREQTCKM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_QTCK_DEL   --事物开始

     set @BillType =   (select BillType  from STOREQTCKM where rtrim(BILLID) = @BILLID)


    declare SM_Consign_QTCK_DEL Cursor for Select GOODSID,DetailBillFlowID,STOREID,REDetailBillFlowID ,QUANTITY  from STOREQTCKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_QTCK_DEL

    fetch SM_Consign_QTCK_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@REDetailBillFlowID,@QUANTITY

    while @@fetch_status = 0            ----开始
    begin

                             DELETE   DetailBillFlow   WHERE  ID=@DetailBillFlowID
       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@STOREID AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
    fetch SM_Consign_QTCK_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@REDetailBillFlowID,@QUANTITY

    END           ------- SM_Consign_QTCK_DEL  WHILE

    close SM_Consign_QTCK_DEL
    deallocate SM_Consign_QTCK_DEL

		DELETE    DetailBillFlow    WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND (YYYYMMBILL in (1,2))
							  AND  BILLTYPE=@billTYPE
------------------------------------以上是删除全部单据明细

   update  STOREQTCKM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_QTCK_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_QTCK_DEL
      set @flagreturn = 0
   end
end








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG






















CREATE PROCEDURE [STORE_QTRK]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---是否现款标志
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @VENDORID   varchar(15)               --明细存货编号
declare @bankID   varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @RATE NUMERIC(20,10)                          --单据总金额
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @SUMAMT NUMERIC(20,10)                          --单据总金额
declare @UNITQTY NUMERIC(20,10)                          --单据总金额
declare @refqty NUMERIC(20,10)                          --引用数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @PRICETYPE INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @JianShu [int] 
declare @MeiJianQty [T_QUANTITY] 
declare @LingTou [T_QUANTITY] 

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

     set @BillDate =   (select BillDate  from STOREQTRKM where rtrim(BILLID) = @BILLID)
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     

    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END

if  (select isnull(flagPost,0) from STOREQTRKM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_QTRK   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREQTRKM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREQTRKM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREQTRKM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREQTRKM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREQTRKM where rtrim(BILLID) = @BILLID)
     set @VENDORID =   (select  VENDORID  from STOREQTRKM where rtrim(BILLID) = @BILLID)
     set @BANKID =   (select BANKID  from STOREQTRKM where rtrim(BILLID) = @BILLID)   ---------付款银行


    declare SM_Consign_QTRK Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(unitPRICE,0) as PRICE, 
                                                                  DetailBillFlowID,UNITQTY,PRICETYPE,JianShu,MeiJianQty,LingTou    from STOREQTRKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_QTRK

    fetch SM_Consign_QTRK into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE, @DetailBillFlowID,@UNITQTY ,@PRICETYPE,@JianShu,@MeiJianQty,@LingTou

    while @@fetch_status = 0            ----开始
    begin

-------缺少检测仓库  明日解决

                     set @MeiJianQty =   (select ISNULL(RATE1,0)  from GOODS where  GOODSID = @GOODSID)


                            IF (ISNULL(@JianShu,0)*ISNULL(@MeiJianQty,0)+ISNULL(@LingTou,0)<>@Unitqty) AND (ISNULL(@JianShu,0)<>0 OR ISNULL(@LingTou,0)<>0)
                                     BEGIN
			      rollback transaction trans_QTRK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='件数*每件数量+零头与数量不等，单据不能记帐'
			    close SM_Consign_QTRK
			    deallocate SM_Consign_QTRK
                                          RETURN
			END
                                      IF NOT (exists (select * from STORE where STOREID=@STOREID))
                                     BEGIN
			      rollback transaction trans_QTRK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close SM_Consign_QTRK
			    deallocate SM_Consign_QTRK
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@STOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_QTRK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_QTRK
			    deallocate SM_Consign_QTRK
                                          RETURN
			END




            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)*0.001  from GOODS where  GOODSID = @GOODSID)

---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	

	IF @PRICETYPE=0  
	BEGIN
		IF   @QTY<>0
		BEGIN
		SET  @PRICE=(@UNITQTY*@PRICE)/@QTY
		END

	END

	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE   ,@DetailBillFlowID  , @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     isnull(@REFQTY,0),0 )    
	          UPDATE   STOREQTRKD  set    DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_QTRK


-----------====================2012-09-04 begin

	IF   @INF_COSTINGTYPEID=6 
	Begin

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,2,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',1,@QTY*@PRICE,null, 
	     isnull(@REFQTY,0),0 )    

-----///===	update DetailBillFlow  where ID=@NEWID
	END
-----------====================2012-09-04 end

--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END


--------------------
    fetch SM_Consign_QTRK into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE, @DetailBillFlowID,@UNITQTY ,@PRICETYPE,@JianShu,@MeiJianQty,@LingTou

    END           ------- SM_Consign_QTRK  WHILE

    close SM_Consign_QTRK
    deallocate SM_Consign_QTRK

   update  STOREQTRKM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
   update  STOREQTRKD  set   AMT  =  Round(ISNULL(quantity,0)*ISNULL(UNITprice,0),2)               where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STOREQTRKD  set   AMT  =  Round(ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)   where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0
    

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_QTRK
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_QTRK
      set @flagreturn = 0
   end
end


















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_QTRK_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @billtype   INT
declare @SFLAG   INT
declare @INF_COSTINGTYPEID  INT                ---本期期初加权价
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间


       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STOREQTRKM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREQTRKM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_QTRK_DEL   --事物开始

	     set @BillType =   (select BillType  from STOREQTRKM where rtrim(BILLID) = @BILLID)

    declare SM_Consign_QTRK_DEL Cursor for Select GOODSID,DetailBillFlowID,STOREID,BILLID    from STOREQTRKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_QTRK_DEL

    fetch SM_Consign_QTRK_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@BILLID

    while @@fetch_status = 0            ----开始
    begin
                             DELETE   DetailBillFlow     WHERE  ID=@DetailBillFlowID
--------------------------------------以上是删除一条单据明细
       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END


		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@STOREID AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
    fetch SM_Consign_QTRK_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@BILLID

    END           ------- SM_Consign_QTRK_DEL  WHILE

    close SM_Consign_QTRK_DEL
    deallocate SM_Consign_QTRK_DEL

                             DELETE   DetailBillFlow     WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 AND BILLTYPE=@billtype
--------------------------------------以上上全部删除单据  是解决多次记帐失败的问题

   update  STOREQTRKM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_QTRK_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_QTRK_DEL
      set @flagreturn = 0
   end
end







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














--------------------------------------------------------------------

CREATE PROCEDURE [STORE_QTSR]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。


declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)

declare @bill_type int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @CLIENTID   varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @SUMAMT NUMERIC(20,10)                          --数量
declare @refqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价

declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @INBANKID VARCHAR(25)
declare @BILLDATE DATEtime
declare @MINBILLDATE DATEtime
declare @MAXBILLDATE DATEtime
declare @B_CODE VARCHAR(25)
declare @V_DATE DATEtime
declare @B_ID INTEGER
declare @STOREHSFS   INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @YYYYMM_FLAG  INTEGER

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @BillDate =   (select BillDate  from STOREQTSRM where rtrim(BILLID) = @BILLID)
    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END



if  (select isnull(flagPost,0) from STOREQTSRM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_QTSR   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREQTSRM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREQTSRM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREQTSRM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREQTSRM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  SFLAG  from STOREQTSRM where rtrim(BILLID) = @BILLID)
     set @INBANKID =   (select  VENDORID  from STOREQTSRM where rtrim(BILLID) = @BILLID)


                                      IF NOT (exists (select * from BANK where BANKID=@INBANKID))
                                     BEGIN
			      rollback transaction trans_QTSR
			      set @flagreturn = 0
                                              SET @RETURNSTRING='银行科目不能为空或银行科目不存在，单据不能记帐'
                                          RETURN
			END
   	 SELECT @SUMAMT= (SELECT SUM(QUANTITY)  FROM  STOREQTSRD   where rtrim(BILLID) = @BILLID)

------------------------------以下是解决科目帐的算法
            IF   (not exists(select *  from BANKBILLFLOW  where 
             		                                    (rtrim(BANKID) = @INBANKID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@INBANKID,
		     0,0,Null,
		     @inoutFlag,0  )    
            END      ------IF   END
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@INBANKID,
		     0,@SUMAMT,Null,
		     1,0  )    
                            execute      BANK_CACULATOR_YYYYMM   @INBANKID,@YYYYMM
------------------------------------

   update  STOREQTSRM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_QTSR
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_QTSR
      set @flagreturn = 0
   end
end






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_QTSR_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 

declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @BANKID    varchar(15)               --明细存货编号
declare @INBANKID    varchar(15)               --明细存货编号
declare @CLIENTID   varchar(30)                     --序列号
declare @INF_COSTINGTYPEID   INT
declare @REFQTY   NUMERIC(20,10)
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STOREQTSRM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREQTSRM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_QTSR_DEL   --事物开始


	     set @INBANKID =   (select  VENDORID  from STOREQTSRM where rtrim(BILLID) = @BILLID)

		DELETE   BANKBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=3
                            execute      BANK_CACULATOR_YYYYMM   @INBANKID,@YYYYMM

   update  STOREQTSRM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_QTSR_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_QTSR_DEL
      set @flagreturn = 0
   end
end






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG









----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_SUM_ALL]  
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @BILLid varchar(15)               --明细存货编号
declare @SUMAMT   NUMERIC(20,10)                          --数量
----------------------不合计盘点单

     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_SUM_ALL   --事物开始


    declare YOUBIAO_QTCK Cursor for Select     BILLID   from STOREQTCKM   where flagpost=0

    Open YOUBIAO_QTCK

    fetch YOUBIAO_QTCK into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREQTCKD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREQTCKM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_QTCK into @BILLID     

    END           ------- YOUBIAO_QTCK  WHILE

    close YOUBIAO_QTCK
    deallocate YOUBIAO_QTCK

---------------------------------------------------
    declare YOUBIAO_QTCKTH Cursor for Select     BILLID   from STOREQTCKTHM   where flagpost=0

    Open YOUBIAO_QTCKTH

    fetch YOUBIAO_QTCKTH into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREQTCKTHD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREQTCKTHM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_QTCKTH into @BILLID     

    END           ------- YOUBIAO_QTCKTH  WHILE

    close YOUBIAO_QTCKTH
    deallocate YOUBIAO_QTCKTH

-------------------------------------------
    declare YOUBIAO_JYCKTH Cursor for Select     BILLID   from STOREJYCKTHM   where flagpost=0

    Open YOUBIAO_JYCKTH

    fetch YOUBIAO_JYCKTH into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREJYCKTHD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREJYCKTHM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_JYCKTH into @BILLID     

    END           ------- YOUBIAO_JYCKTH  WHILE

    close YOUBIAO_JYCKTH
    deallocate YOUBIAO_JYCKTH

-------------------------------------------------------------
    declare YOUBIAO_JYCK Cursor for Select     BILLID   from STOREJYCKM   where flagpost=0

    Open YOUBIAO_JYCK

    fetch YOUBIAO_JYCK into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREJYCKD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREJYCKM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_JYCK into @BILLID     

    END           ------- YOUBIAO_JYCK  WHILE

    close YOUBIAO_JYCK
    deallocate YOUBIAO_JYCK

-------------------------------------------------------------
    declare YOUBIAO_DBCK Cursor for Select     BILLID   from STOREDBCKM   where flagpost=0

    Open YOUBIAO_DBCK

    fetch YOUBIAO_DBCK into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREDBCKD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREDBCKM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_DBCK into @BILLID     

    END           ------- YOUBIAO_DBCK  WHILE

    close YOUBIAO_DBCK
    deallocate YOUBIAO_DBCK

-------------------------------------------------------------
    declare YOUBIAO_DBCKTH Cursor for Select     BILLID   from STOREDBCKTHM   where flagpost=0

    Open YOUBIAO_DBCKTH

    fetch YOUBIAO_DBCKTH into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREDBCKTHD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREDBCKTHM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_DBCKTH into @BILLID     

    END           ------- YOUBIAO_DBCKTH  WHILE

    close YOUBIAO_DBCKTH
    deallocate YOUBIAO_DBCKTH

-------------------------------------------------------------

    declare YOUBIAO_JYRKTH Cursor for Select     BILLID   from STOREJYRKTHM   where flagpost=0

    Open YOUBIAO_JYRKTH

    fetch YOUBIAO_JYRKTH into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREJYRKTHD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREJYRKTHM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_JYRKTH into @BILLID     

    END           ------- YOUBIAO_JYRKTH  WHILE

    close YOUBIAO_JYRKTH
    deallocate YOUBIAO_JYRKTH

-------------------------------------------------------------
    declare YOUBIAO_JYRK Cursor for Select     BILLID   from STOREJYRKM   where flagpost=0

    Open YOUBIAO_JYRK

    fetch YOUBIAO_JYRK into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREJYRKD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREJYRKM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_JYRK into @BILLID     

    END           ------- YOUBIAO_JYRK  WHILE

    close YOUBIAO_JYRK
    deallocate YOUBIAO_JYRK

-------------------------------------------------------------
    declare YOUBIAO_DBRK Cursor for Select     BILLID   from STOREDBRKM   where flagpost=0

    Open YOUBIAO_DBRK

    fetch YOUBIAO_DBRK into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREDBRKD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREDBRKM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_DBRK into @BILLID     

    END           ------- YOUBIAO_DBRK  WHILE

    close YOUBIAO_DBRK
    deallocate YOUBIAO_DBRK

-------------------------------------------------------------
    declare YOUBIAO_ZSRK Cursor for Select     BILLID   from STOREZSRKM   where flagpost=0

    Open YOUBIAO_ZSRK

    fetch YOUBIAO_ZSRK into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREZSRKD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREZSRKM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_ZSRK into @BILLID     

    END           ------- YOUBIAO_ZSRK  WHILE

    close YOUBIAO_ZSRK
    deallocate YOUBIAO_ZSRK

-------------------------------------------------------------
    declare YOUBIAO_QTRK Cursor for Select     BILLID   from STOREQTRKM   where flagpost=0

    Open YOUBIAO_QTRK

    fetch YOUBIAO_QTRK into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREQTRKD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREQTRKM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_QTRK into @BILLID     

    END           ------- YOUBIAO_QTRK  WHILE

    close YOUBIAO_QTRK
    deallocate YOUBIAO_QTRK

-------------------------------------------------------------

    declare YOUBIAO_DBRKTH Cursor for Select     BILLID   from STOREDBRKTHM   where flagpost=0

    Open YOUBIAO_DBRKTH

    fetch YOUBIAO_DBRKTH into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREDBRKTHD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREDBRKTHM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_DBRKTH into @BILLID     

    END           ------- YOUBIAO_DBRKTH  WHILE

    close YOUBIAO_DBRKTH
    deallocate YOUBIAO_DBRKTH

-------------------------------------------------------------
    declare YOUBIAO_ZSRKTH Cursor for Select     BILLID   from STOREZSRKTHM   where flagpost=0

    Open YOUBIAO_ZSRKTH

    fetch YOUBIAO_ZSRKTH into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREZSRKTHD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREZSRKTHM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_ZSRKTH into @BILLID     

    END           ------- YOUBIAO_ZSRKTH  WHILE

    close YOUBIAO_ZSRKTH
    deallocate YOUBIAO_ZSRKTH

-------------------------------------------------------------

    declare YOUBIAO_QTRKTH Cursor for Select     BILLID   from STOREQTRKTHM   where flagpost=0

    Open YOUBIAO_QTRKTH

    fetch YOUBIAO_QTRKTH into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREQTRKTHD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREQTRKTHM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_QTRKTH into @BILLID     

    END           ------- YOUBIAO_QTRKTH  WHILE

    close YOUBIAO_QTRKTH
    deallocate YOUBIAO_QTRKTH

-------------------------------------------------------------

    declare YOUBIAO_GJRK Cursor for Select     BILLID   from STOREGJRKM   where flagpost=0

    Open YOUBIAO_GJRK

    fetch YOUBIAO_GJRK into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STOREGJRKD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREGJRKM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_GJRK into @BILLID     

    END           ------- YOUBIAO_GJRK  WHILE

    close YOUBIAO_GJRK
    deallocate YOUBIAO_GJRK

-------------------------------------------------------------
    declare YOUBIAO_XSCK Cursor for Select     BILLID   from STOREXSCKM   where flagpost=0

    Open YOUBIAO_XSCK

    fetch YOUBIAO_XSCK into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE*DISC*0.01*(100+ISNULL(TAXRATE,0))*0.01,2))  as sumamt  from  STOREXSCKD 
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREXSCKM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_XSCK into @BILLID     

    END           ------- YOUBIAO_XSCK  WHILE

    close YOUBIAO_XSCK
    deallocate YOUBIAO_XSCK

-------------------------------------------------------------
    declare YOUBIAO_XSTH Cursor for Select     BILLID   from STOREXSTHM   where flagpost=0

    Open YOUBIAO_XSTH

    fetch YOUBIAO_XSTH into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE*DISC*0.01*(100+ISNULL(TAXRATE,0))*0.01,2))  as sumamt  from  STOREXSTHD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREXSTHM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_XSTH into @BILLID     

    END           ------- YOUBIAO_XSTH  WHILE

    close YOUBIAO_XSTH
    deallocate YOUBIAO_XSTH


----------------------    declare YOUBIAO_CGTH Cursor for Select     BILLID   from STORECGTHM   where flagpost=0

    Open YOUBIAO_CGTH

    fetch YOUBIAO_CGTH into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE*DISC*0.01*(100+ISNULL(TAXRATE,0))*0.01,2))  as sumamt  from   STORECGTHD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STORECGTHM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_CGTH into @BILLID     

    END           ------- YOUBIAO_CGTH  WHILE

    close YOUBIAO_CGTH
    deallocate YOUBIAO_CGTH

-----------------------------------------
    declare YOUBIAO_CGRK Cursor for Select     BILLID   from STORECGRKM   where flagpost=0

    Open YOUBIAO_CGRK

    fetch YOUBIAO_CGRK into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE*DISC*0.01*(100+ISNULL(TAXRATE,0))*0.01,2))  as sumamt  from   STORECGRKD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STORECGRKM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_CGRK into @BILLID     

    END           ------- YOUBIAO_CGRK  WHILE

    close YOUBIAO_CGRK
    deallocate YOUBIAO_CGRK

----------------------------------------------------------------

-------------------------------------------------------------

    declare YOUBIAO_CKDB Cursor for Select     BILLID   from STORECKDBM   where flagpost=0

    Open YOUBIAO_CKDB

    fetch YOUBIAO_CKDB into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE,2))  as sumamt  from  STORECKDBD
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STORECKDBM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_CKDB into @BILLID     

    END           ------- YOUBIAO_CKDB  WHILE

    close YOUBIAO_CKDB
    deallocate YOUBIAO_CKDB

-------------------------------------------------------------
    declare YOUBIAO_XSDD Cursor for Select     BILLID   from STOREXSDDM   where flagpost=0

    Open YOUBIAO_XSDD

    fetch YOUBIAO_XSDD into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE*DISC*0.01*(100+ISNULL(TAXRATE,0))*0.01,2))  as sumamt  from  STOREXSDDD 
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STOREXSDDM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_XSDD into @BILLID     

    END           ------- YOUBIAO_XSDD  WHILE

    close YOUBIAO_XSDD
    deallocate YOUBIAO_XSDD

-------------------------------------------------------------
    declare YOUBIAO_CGDD Cursor for Select     BILLID   from STORECGDDM   where flagpost=0

    Open YOUBIAO_CGDD

    fetch YOUBIAO_CGDD into @BILLID     


    while @@fetch_status = 0            ----开始
    begin
 	SET @SUMAMT=(select  sum(Round(UNITQTY*UNITPRICE*DISC*0.01*(100+ISNULL(TAXRATE,0))*0.01,2))  as sumamt  from  STORECGDDD 
	                                 where  ltrim(rtrim(BILLID)) = @BILLID   )

	   update  STORECGDDM  set  SUMAMT = @SUMAMT     where ltrim(rtrim(BILLID)) = @BILLID 
	
	    fetch YOUBIAO_CGDD into @BILLID     

    END           ------- YOUBIAO_CGDD  WHILE

    close YOUBIAO_CGDD
    deallocate YOUBIAO_CGDD

-------------------------------------------------------------
    

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_SUM_ALL
   end
   else
   begin
      rollback transaction trans_SUM_ALL
   end






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG




















----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_TALLY]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @TABLENAME varchar(22),      ---表名
                  @RETURNSTRING00            varchar(60)    output ,      ---单据编号   
                  @flagreturn00 int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 

declare @YYYYMM varchar(6)                   --会计年月     
declare @GOODSID varchar(30)                   --会计年月     

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')   

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREZFDM'
         BEGIN
                 execute  STORE_ZFD    @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END  
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREXSFPM'
         BEGIN
                 execute  STORE_XSFP    @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END  
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECGFPM'
         BEGIN
                 execute  STORE_CGFP    @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END  

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREXSDDM'
         BEGIN
                 execute  STORE_XSDD    @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END  

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECGDDM'
         BEGIN
                 execute  STORE_CGDD    @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END  

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORELIUHM'
         BEGIN
                 execute  STORE_LIUH    @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END  

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREGJRKM'
         BEGIN
                 execute  STORE_GJRK    @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
         IF  @TABLENAME = 'STORECGTHM'
         BEGIN
                 execute  STORE_CGTH      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREXSTHM'
         BEGIN
                 execute  STORE_XSTH      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREMOVEM'
         BEGIN
                 execute  STORE_MOVE      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREXSSKM'
         BEGIN
                 execute  STORE_XSSK      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECGFKM'
         BEGIN
                 execute  STORE_CGFK      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREXSCKM'
         BEGIN
                 execute  STORE_XSCK     @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREQTRKM'
         BEGIN
                 execute  STORE_QTRK    @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREQTCKM'
         BEGIN
                 execute  STORE_QTCK     @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREQTSRM'
         BEGIN
                 execute  STORE_QTSR     @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREFYKZM'
         BEGIN
                 execute  STORE_FYKZ    @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECKDBM'
         BEGIN
                 execute  STORE_CKDB     @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECSHM'
         BEGIN
                 execute  STORE_CSH     @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECGRKM'
         BEGIN
                 execute  STORE_CGRK     @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
        END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREYunFeiFKM'
         BEGIN
                 execute  STORE_YunFeiFK     @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
        END
-----------------------------------------------------IF  END

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECKPDM'
         BEGIN
                 execute  STORE_CKPD     @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREQGDM'
         BEGIN
                 execute  STORE_QGD     @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREJGDM'
         BEGIN
                 execute  STORE_JGD     @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREQGADM'
         BEGIN
                 execute  STORE_QGAD     @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END











----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG
























----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_TALLY_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @TABLENAME varchar(22),      ---表名
                  @RETURNSTRING00            varchar(60)    output ,      ---单据编号   
                  @flagreturn00 int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 

declare @YYYYMM varchar(6)                   --会计年月     
declare @GOODSID varchar(30)                   --会计年月     

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')



-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREXSDDM'
         BEGIN
                 execute  STORE_XSDD_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END     

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORELIUHM'
         BEGIN
                 execute  STORE_LIUH_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END     

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREGJRKM'
         BEGIN
                 execute  STORE_GJRK_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREXSTHM'
         BEGIN
                 execute  STORE_XSTH_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECGTHM'
         BEGIN
                 execute  STORE_CGTH_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREMOVEM'
         BEGIN
                 execute  STORE_MOVE_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREXSSKM'
         BEGIN
                 execute  STORE_XSSK_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECGFKM'
         BEGIN
                 execute  STORE_CGFK_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREYunFeiFKM'
         BEGIN
                 execute  STORE_YunFeiFK_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECGRKM'
         BEGIN
                 execute  STORE_CGRK_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREXSCKM'
         BEGIN
                 execute  STORE_XSCK_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREQTRKM'
         BEGIN
                 execute  STORE_QTRK_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREQTCKM'
         BEGIN
                 execute  STORE_QTCK_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREQTSRM'
         BEGIN
                 execute  STORE_QTSR_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREFYKZM'
         BEGIN
                 execute  STORE_FYKZ_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECKDBM'
         BEGIN
                 execute  STORE_CKDB_DEL     @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECKPDM'
         BEGIN
                 execute  STORE_CKPD_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECSHM'
         BEGIN
                 execute  STORE_CSH_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREJGDM'
         BEGIN
                 execute  STORE_JGD_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREQGDM'
         BEGIN
                 execute  STORE_QGD_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREQGADM'
         BEGIN
                 execute  STORE_QGAD_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECGDDM'
         BEGIN
                 execute  STORE_CGDD_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END
-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREXSFPM'
         BEGIN
                 execute  STORE_XSFP_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STORECGFPM'
         BEGIN
                 execute  STORE_CGFP_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END

-------------------------------IF BEGIN
         IF  @TABLENAME = 'STOREZFDM'
         BEGIN
                 execute  STORE_ZFD_DEL      @BILLID,@returnSTRING = @RETURNSTRING00  output,@flagreturn = @flagreturn00  output
         END
-----------------------------------------------------IF  END











----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG






----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[STORE_XSCK]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @BuMenID varchar(10)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ClientFlag int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ITEMNO varchar(15)               --明细存货编号
declare @YunShuDWID varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号、
declare @CLIENTID varchar(15)               --明细存货编号、
declare @VENDORID varchar(15)               --明细存货编号、
declare @BANKID varchar(15)               --明细存货编号、
declare @SUMAMT  NUMERIC(20,10)               --明细存货编号、
declare @RATE  NUMERIC(20,10)               --明细存货编号、
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @STOREIDEqty NUMERIC(20,10)                          --仓库数量
declare @REFqty NUMERIC(20,10)                          --数量
declare @UNITqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @PRICETYPE  NUMERIC(20,10)               --含税单价
declare @KEYONGunitQTY  NUMERIC(20,10)               --含税单价
declare @KEYONGquantity  NUMERIC(20,10)               --含税单价
declare @TMPunitQTY  NUMERIC(20,10)               --含税单价
declare @TMPquantity  NUMERIC(20,10)               --含税单价
declare @TAXRATE NUMERIC(20,10)               --含税单价
declare @APRICE  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID  varchar(50)
declare @GOODSNAME varchar(30)                     --序列号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @REITEMNO VARCHAR(25)
declare @BILLDATE DATEtime
declare @SFLAG  INTEGER
declare @YYYYMM_FLAG  INTEGER
declare @count  INTEGER
declare @ChaCheSID VARCHAR(25)
declare @PanYunSID VARCHAR(25)
declare @YunFeiZhiFuFX VARCHAR(25)  ----运费支付方向
declare @ChaChePrice  NUMERIC(20,10)               --含税单价
declare @PanYunPrice  NUMERIC(20,10)               --含税单价
declare @ChaCheSYunfei  NUMERIC(20,10)               --含税单价
declare @PanYunSYunfei  NUMERIC(20,10)               --含税单价
declare @QiTaFeiYong  NUMERIC(20,10)               --含税单价
declare @YunFeiSum  NUMERIC(20,10)               --含税单价
declare @MaxRate  NUMERIC(20,10)               --含税单价
declare @MinRate  NUMERIC(20,10)               --含税单价
declare @DMinSPrice NUMERIC(20,10)               --含税单价

declare @STOREHSFS   INTEGER
declare @ZhongLiangXZ   INTEGER
declare @XSPriceXZ   INTEGER
declare @NEGCLOSEOFF   bit
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @JianShu [int] 
declare @MeiJianQty [T_QUANTITY] 
declare @LingTou [T_QUANTITY] 


       SELECT    @NEGCLOSEOFF=(SELECT  NEGCLOSEOFF  FROM   ACCINFO    WHERE   GUID='0001' )           

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )  
         


set @BILLID   = ltrim(rtrim(@BILLID))
SET  @RETURNSTRING='  '
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @ZhongLiangXZ   = (select optionvalue from accoptions where optionname ='ZhongLiangXZ')     
     set @XSPriceXZ   = (select optionvalue from accoptions where optionname ='XSPriceXZ')     

     set @BillDate =   (select BillDate  from STOREXSCKM where rtrim(BILLID) = @BILLID)

    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 


      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END


if  (select isnull(flagPost,0) from STOREXSCKM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_XSCK   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREXSCKM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREXSCKM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREXSCKM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREXSCKM where rtrim(BILLID) = @BILLID)
     set @CLIENTID =   (select CLIENTID  from STOREXSCKM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREXSCKM where rtrim(BILLID) = @BILLID)
     set @ClientFLAG =   (select  ISNULL(ClientFLAG,1)   from STOREXSCKM where rtrim(BILLID) = @BILLID)
     set @BANKID =   (select BANKID  from  STOREXSCKM where rtrim(BILLID) = @BILLID)   ---------收款银行
     set @BuMenID =   (select BuMenID  from  STOREXSCKM where rtrim(BILLID) = @BILLID)   ---------收款银行

     set @ChaCheSID =   (select ChaCheSID  from STOREXSCKM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @PanYunSID =   (select PanYunSID  from STOREXSCKM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @YunFeiZhiFuFX =   (select YunFeiZhiFuFX  from STOREXSCKM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @ChaChePrice =   (select ISNULL(ChaChePrice,0)  from STOREXSCKM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @PanYunPrice =   (select ISNULL(PanYunPrice,0)  from STOREXSCKM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @ChaCheSYunFei=    (select ROUND(ISNULL(ChaChePrice,0)*SumQUANTITY,2) from STOREXSCKM where rtrim(BILLID) = @BILLID)   ---------付款银行 
     set @PanYunSYunFei=    (select ROUND(ISNULL(PanYunPrice,0)*SumQUANTITY,2) from STOREXSCKM where rtrim(BILLID) = @BILLID)   ---------付款银行 
     set @YunFeiSum=   @ChaCheSYunFei+@PanYunSYunFei
     set @QiTaFeiYong =   (select ISNULL(QiTaFeiYong,0)  from STOREXSCKM where rtrim(BILLID) = @BILLID)   ---------付款银行


   	 SELECT @SUMAMT= (SELECT SUM(ROUND(DISC*0.01*unitprice*UNITQTY*(1+ISNULL(TAXRATE,0)*0.01),2)) FROM   STOREXSCKD  where rtrim(BILLID) = @BILLID)
   	 SELECT @SUMAMT=0

                              IF (NOT exists(select * from YunShuDW where YunShuDWID=@ChaCheSID)) and @ChaChePrice<>0
                              BEGIN
			      rollback transaction trans_CGRK
			      set @flagreturn = 0
                                      SET @RETURNSTRING='叉车商不能为空或叉车商不存在，单据不能记帐'
                                       RETURN
			END

                              IF (NOT exists(select * from YunShuDW where YunShuDWID=@PanYunSID)) and @PanYunPrice<>0
                              BEGIN
			      rollback transaction trans_CGRK
			      set @flagreturn = 0
                                      SET @RETURNSTRING='盘运商不能为空或盘运商不存在，单据不能记帐'
                                       RETURN
			END

                                      IF NOT (exists (select * from ViewCLIENT where CLIENTID=@CLIENTID   and CLIENTFLAG=@CLIENTFLAG))
                                     BEGIN
			      rollback transaction  trans_XSCK 
			      set @flagreturn = 0
                                              SET @RETURNSTRING='客户不能为空或客户不存在，单据不能记帐'
                                          RETURN
			END


                       IF @SFLAG=1 and @ClientFLAG=0
                       BEGIN
			      rollback transaction  trans_XSCK 
			      set @flagreturn = 0
                              SET @RETURNSTRING='当客户为供应商的时候，不允许选择现款销售，单据不能记帐'
                              RETURN
		       END



    declare SM_Consign_XSCK Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(UNITPRICE,0)*ISNULL(DISC,0)*0.01 as PRICE, 
                                                                   REDetailBillFlowID,ISNULL(UNITQTY,0) AS UNITQTY  ,PRICETYPE,TAXRATE,JianShu,MeiJianQty,LingTou,REITEMNO  from STOREXSCKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_XSCK

    fetch SM_Consign_XSCK into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY,@PRICETYPE,@TAXRATE,@JianShu,@MeiJianQty,@LingTou,@REITEMNO 

    while @@fetch_status = 0            ----开始
    begin

                     set @MeiJianQty =   (select ISNULL(RATE1,0)  from GOODS where  GOODSID = @GOODSID)


                            IF (ISNULL(@JianShu,0)*ISNULL(@MeiJianQty,0)+ISNULL(@LingTou,0)<>@Unitqty) AND (ISNULL(@JianShu,0)<>0 OR ISNULL(@LingTou,0)<>0)
                                     BEGIN
			      rollback transaction trans_XSCK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='件数*每件数量+零头与数量不等，单据不能记帐'
			    close  SM_Consign_XSCK
			    deallocate  SM_Consign_XSCK
                                          RETURN
			END

            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)*0.001  from GOODS where  GOODSID = @GOODSID)

----------------订单处理引用begin

	IF @REITEMNO IS NOT NULL
    BEGIN
	         SELECT   @KEYONGunitQTY = UNITQTY-ISNULL(WCunitQTY,0)   FROM   STOREXSDDD    WHERE  ITEMNO=@REITEMNO
	         SELECT   @KEYONGquantity = quantity-ISNULL(WCquantity,0)   FROM   STOREXSDDD    WHERE  ITEMNO=@REITEMNO
        IF @KEYONGunitQTY >0  or @KEYONGquantity>0
		BEGIN
		   UPDATE   STOREXSDDD   SET WCunitQTY=ISNULL(WCunitQTY,0)+ISNULL(@UNITQTY,0)  WHERE  ITEMNO=@REITEMNO
		   UPDATE   STOREXSDDD   SET WCquantity=ISNULL(WCquantity,0)+ISNULL(@qty,0)  WHERE  ITEMNO=@REITEMNO
		   
			SELECT @TMPunitQTY=SUM(UNITQTY-isnull(WCunitQTY,0))  FROM STOREXSDDD   WHERE  BILLID IN (SELECT BILLID FROM   STOREXSDDD WHERE  ITEMNO=@REITEMNO)
			SELECT @TMPquantity=SUM(quantity-isnull(WCquantity,0))  FROM STOREXSDDD   WHERE  BILLID IN (SELECT BILLID FROM   STOREXSDDD WHERE  ITEMNO=@REITEMNO)
			IF @TMPunitQTY<=0  OR @TMPquantity <= 0
			BEGIN
			   UPDATE   STOREXSDDM   SET STATUS=1  WHERE  BILLID IN (SELECT BILLID FROM   STOREXSDDD WHERE  ITEMNO=@REITEMNO)
			END
		END
		ELSE
		BEGIN
			    set @flagreturn = 0
                SET @RETURNSTRING='引用的订单已经完成或终止，请重新修改单据'
			    close  SM_Consign_XSCK
			    deallocate  SM_Consign_XSCK
			    rollback transaction trans_XSCK
                RETURN
		END
	END

----------------订单处理引用end


---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	


	IF @PRICETYPE=1   
	BEGIN
   	 SELECT @SUMAMT=@SUMAMT+ROUND(@price*@QTY*(1+ISNULL(@TAXRATE,0)*0.01),2)
	END
	IF @PRICETYPE=0  
	BEGIN
   	 SELECT @SUMAMT=@SUMAMT+ROUND(@price*@UNITQTY*(1+ISNULL(@TAXRATE,0)*0.01),2)

		IF   @QTY<>0
		BEGIN
		SET  @PRICE=(@UNITQTY*@PRICE)/@QTY
		END

	END



------------------------------------------

                                        IF NOT (exists (select * from STORE where STOREID=@STOREID))
                                     BEGIN
			      rollback transaction trans_XSCK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close  SM_Consign_XSCK
			    deallocate  SM_Consign_XSCK
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@STOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_XSCK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_XSCK
			    deallocate SM_Consign_XSCK
                                          RETURN
			END




--------------------------------------------
------------更改为数量库存报警
------------
			declare @FuKuCunOUTQty int    ---1代表数量提示，0代表重量提示
			declare @BiJiaoQTY  NUMERIC(20,10)  ---比较过度用的变量


		        set @FuKuCunOUTQty  = (select optionvalue from accoptions where optionname ='FuKuCunOUTQty')     
		
                        IF    @NEGCLOSEOFF=0 
			BEGIN 
				IF @FuKuCunOUTQty=1
				BEGIN 
	                             	EXEC   GETGOODSIDMEQTY  @STOREID,@GOODSID,@YYYYMM,@MEQTY=@STOREIDEQTY   OUTPUT
					SET @BiJiaoQTY=@UNITQTY
				END
				ELSE
				BEGIN 
	                             	EXEC   GETGOODSIDEQTY  @STOREID,@GOODSID,@YYYYMM,@EQTY=@STOREIDEQTY   OUTPUT				
					SET @BiJiaoQTY=@QTY
				END
                                IF @BiJiaoQTY >  ISNULL(@STOREIDEQTY,0)
	                        BEGIN
                     		                  SET  @GOODSNAME =(SELECT code+'  '+NAME+'  '+Specname as GoodsName FROM GOODS WHERE GOODSID=@GOODSID)
				      rollback transaction trans_XSCK
				      set @flagreturn = 0
             		                                 SET @RETURNSTRING='此'+@GOODSNAME+'库存不足不能记帐'
				    close  SM_Consign_XSCK
				    deallocate  SM_Consign_XSCK
	                                          RETURN
				END
			END

--------------------------------------------

            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)

	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE ,@REDetailBillFlowID,  @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@StoreID,'F',-1,@QTY*@PRICE,null,
	     0,0   )    
--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

                      select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID         -----------反填的是吨价格
	          UPDATE     STOREXSCKD     set    APRICE=@APRICE,  DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_XSCK

--------------------
    fetch SM_Consign_XSCK into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY,@PRICETYPE,@TAXRATE ,@JianShu,@MeiJianQty,@LingTou,@REITEMNO


    END           ------- SM_Consign_XSCK  WHILE

    close SM_Consign_XSCK
    deallocate SM_Consign_XSCK

-------------------
-------------------运费结算开始

          IF  @ChaChePrice<>0
	   begin
		set @YunShuDWID=@ChaCheSID
	            IF   (not exists(select *  from YunShuDWBILLFLOW  where 
             		                                    (rtrim(YunShuDWID) = @YunShuDWID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@YunShuDWID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
	             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@YunShuDWID,
		     0,@ChaCheSYunFei,Null,
		     1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      YunShuDW_CACULATOR_YYYYMM   @YunShuDWID,@YYYYMM

	    end

            IF  @PanYunPrice<>0
	    begin
		set @YunShuDWID=@PanYunSID

	            IF   (not exists(select *  from YunShuDWBILLFLOW  where 
             		                                    (rtrim(YunShuDWID) = @YunShuDWID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@YunShuDWID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
	             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@YunShuDWID,
		     0,@PanYunSYunFei,Null,
		     1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      YunShuDW_CACULATOR_YYYYMM   @YunShuDWID,@YYYYMM

	        end

-------------------运费结算结束
        set @SUMAMT=@SUMAMT+@QiTaFeiYong

        IF @YunFeiZhiFuFX='我方垫付运费' 
        begin
        set @SUMAMT=@SUMAMT+@YunFeiSum
        end


-------------------

	IF @SFLAG=0  and  @ClientFLAG=1
	BEGIN
	            IF   (not exists(select *  from CLIENTBILLFLOW  where 
             		                                    (rtrim(CLIENTID) = @CLIENTID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE, CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode, @CLIENTID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE, CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT ,BuMenID  )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode, @CLIENTID,
		     0,@SUMAMT,Null,
		     1,0, @BuMenID )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM
	END         ---------------IF @SFLAG=0






	IF @SFLAG=0  and  @ClientFLAG=0
	BEGIN

	      SET @VendorID=@ClientID
	            IF   (not exists(select *  from VENDORBILLFLOW  where 
             		                                    (rtrim(VENDORID) = @VENDORID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
	             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,-@SUMAMT,Null,
		     1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM

	END     ----------------     IF @SFLAG=0


----------------------
	IF @SFLAG=1  AND  NOT( @BANKID='APSOFT')
	BEGIN

            IF   (not exists(select *  from BANKBILLFLOW  where 
             		                                    (rtrim(BANKID) = @BANKID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,0,Null,
		     @inoutFlag,0  )    
            END      ------IF   END
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,@SUMAMT,Null,
		     1,0  )    
                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM         update  STOREXSCKM  set  DISCAMT=VendorHKSum           where ltrim(rtrim(BILLID)) = @BILLID 

	END     ----------IF @SFLAG=1

   update  STOREXSCKM  set  flagPost = 1,YYYYMM =@BILLYYYYMM   ,SUMAMT=VendorHKSum ,INVOICEAMT=0          where ltrim(rtrim(BILLID)) = @BILLID 
   update  STOREXSCKD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)          where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STOREXSCKD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)   where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_XSCK
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_XSCK
      set @flagreturn = 0
   end
end

























----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG


















----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[STORE_XSCK_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare  @INF_COSTINGTYPEID  INT
declare  @ClientFlag  INT
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @CLIENTID varchar(10)                   --单句会计年月     
declare @VENDORID varchar(10)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @ChaCheSID VARCHAR(25)
declare @PanYunSID VARCHAR(25)

declare @STOREID    varchar(15)               --明细存货编号
declare @REDetailBillFlowID   varchar(30)                     --序列号
declare @REITEMNO   varchar(30)                     --序列号
declare @QUANTITY   NUMERIC(20,10)                     --序列号
declare @UNITQTY   NUMERIC(20,10)                     --序列号
declare @BILLTYPE   INTEGER
declare @SFLAG   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

                                              SET @RETURNSTRING='   '


	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STOREXSCKM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREXSCKM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_XSCK_DEL   --事物开始

     set @BillType =   (select BillType  from STOREXSCKM where rtrim(BILLID) = @BILLID)

			   IF exists (select * from STOREXSSKD  where REBILLID= @BILLID and rebilltype=2    )
			BEGIN
                                              SET @RETURNSTRING=' 此单据已经被销售收款单引用不能取消记帐！  '
			      rollback transaction trans_XSCK_DEL
			      set @flagreturn = 0
                                         RETURN
			END
			   IF exists (select * from STOREXSFPD  where REBILLID= @BILLID     )
			BEGIN
                              SET @RETURNSTRING=' 此单据已经被销售发票单引用不能取消记帐！  '
			      rollback transaction trans_XSCK_DEL
			      set @flagreturn = 0
                                         RETURN
			END



    declare SM_Consign_XSCK_DEL Cursor for Select GOODSID,DetailBillFlowID,STOREID,REDetailBillFlowID ,QUANTITY,UNITQTY,REITEMNO   from STOREXSCKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_XSCK_DEL

    fetch SM_Consign_XSCK_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@REDetailBillFlowID,@QUANTITY,@UNITQTY,@REITEMNO

    while @@fetch_status = 0            ----开始
    begin

                             DELETE   DetailBillFlow   WHERE  ID=@DetailBillFlowID
       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID
       
----------------订单处理引用begin

	IF @REITEMNO IS NOT NULL
    BEGIN
		   UPDATE   STOREXSDDD   SET WCunitQTY=ISNULL(WCunitQTY,0)-ISNULL(@UNITQTY,0)  WHERE  ITEMNO=@REITEMNO
		   UPDATE   STOREXSDDD   SET WCquantity=ISNULL(WCquantity,0)-ISNULL(@QUANTITY,0)  WHERE  ITEMNO=@REITEMNO
  		   UPDATE   STOREXSDDM   SET STATUS=0  WHERE  BILLID IN (SELECT BILLID FROM   STOREXSDDD WHERE  ITEMNO=@REITEMNO)
	END

----------------订单处理引用end

       
       
       
       
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@STOREID AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
    fetch SM_Consign_XSCK_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@REDetailBillFlowID,@QUANTITY,@UNITQTY,@REITEMNO

    END           ------- SM_Consign_XSCK_DEL  WHILE

    close SM_Consign_XSCK_DEL
    deallocate SM_Consign_XSCK_DEL

		DELETE    DetailBillFlow    WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@billTYPE
------------------------------------以上是删除全部单据明细

	     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREXSCKM where rtrim(BILLID) = @BILLID)
	     set @BANKID =   (select BANKID  from  STOREXSCKM where rtrim(BILLID) = @BILLID)   ---------收款银行
		SELECT @CLIENTID=(SELECT CLIENTID FROM   STOREXSCKM    where ltrim(rtrim(BILLID)) = @BILLID  )
	     set @CLIENTFLAG =   (select  ISNULL(CLIENTFLAG,1)  from STOREXSCKM  where rtrim(BILLID) = @BILLID)



     set @ChaCheSID =   (select ChaCheSID  from STOREXSCKM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @PanYunSID =   (select PanYunSID  from STOREXSCKM where rtrim(BILLID) = @BILLID)   ---------付款银行


		DELETE   YunShuDWBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@BILLTYPE
    		         execute      YunShuDW_CACULATOR_YYYYMM   @ChaCheSID,@YYYYMM
    		         execute      YunShuDW_CACULATOR_YYYYMM   @PanYunSID,@YYYYMM


	IF     @SFLAG=0  and @ClientFlag=1
	BEGIN
		DELETE   CLIENTBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@billTYPE
                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM
	END

		IF @SFLAG=0   and  @ClientFlag=0
		BEGIN

		      SET @VendorID=@ClientID
			DELETE   VENDORBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@BILLTYPE
             		               execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM
	                             DELETE  VENDORBILLFLOW    WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 AND BILLTYPE=@billtype
--------------------------------------以上上全部删除单据  是解决多次记帐失败的问题

		END     


	IF     @SFLAG=1
	BEGIN
		DELETE   BANKBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@billTYPE
                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM
	END


   update  STOREXSCKM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_XSCK_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_XSCK_DEL
      set @flagreturn = 0
   end
end

----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG







----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[STORE_XSDD]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ClientFlag int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ITEMNO varchar(15)               --明细存货编号
declare @YunShuDWID varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号、
declare @CLIENTID varchar(15)               --明细存货编号、
declare @VENDORID varchar(15)               --明细存货编号、
declare @INStoreID varchar(15)               --明细存货编号、
declare @SUMAMT  NUMERIC(20,10)               --明细存货编号、
declare @RATE  NUMERIC(20,10)               --明细存货编号、
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @STOREIDEqty NUMERIC(20,10)                          --仓库数量
declare @REFqty NUMERIC(20,10)                          --数量
declare @UNITqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @PRICETYPE  NUMERIC(20,10)               --含税单价
declare @KEYONGQTY  NUMERIC(20,10)               --含税单价
declare @TAXRATE NUMERIC(20,10)               --含税单价
declare @APRICE  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID  varchar(50)
declare @GOODSNAME varchar(30)                     --序列号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @REITEMNO VARCHAR(25)
declare @BILLDATE DATEtime
declare @SFLAG  INTEGER
declare @YYYYMM_FLAG  INTEGER
declare @count  INTEGER
declare @MaxRate  NUMERIC(20,10)               --含税单价
declare @MinRate  NUMERIC(20,10)               --含税单价
declare @DMinSPrice NUMERIC(20,10)               --含税单价

declare @STOREHSFS   INTEGER
declare @ZhongLiangXZ   INTEGER
declare @XSPriceXZ   INTEGER
declare @NEGCLOSEOFF   bit
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @JianShu [int] 
declare @MeiJianQty [T_QUANTITY] 
declare @LingTou [T_QUANTITY] 

       SELECT    @NEGCLOSEOFF=(SELECT  NEGCLOSEOFF  FROM   ACCINFO    WHERE   GUID='0001' )           

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )  
         


set @BILLID   = ltrim(rtrim(@BILLID))
SET  @RETURNSTRING='  '
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @ZhongLiangXZ   = (select optionvalue from accoptions where optionname ='ZhongLiangXZ')     
     set @XSPriceXZ   = (select optionvalue from accoptions where optionname ='XSPriceXZ')     

     set @BillDate =   (select BillDate  from STOREXSDDM where rtrim(BILLID) = @BILLID)

    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 


      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END


if  (select isnull(flagPost,0) from STOREXSDDM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_XSDD   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREXSDDM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREXSDDM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREXSDDM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREXSDDM where rtrim(BILLID) = @BILLID)
     set @CLIENTID =   (select CLIENTID  from STOREXSDDM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREXSDDM where rtrim(BILLID) = @BILLID)
-----------@SFLAG  是否终止 ，1为终止
-----------@status 订单完成标志
     set @INStoreID =   (select PAYTYPEID  from  STOREXSDDM where rtrim(BILLID) = @BILLID)   ---------收款银行

     set @ClientFLAG =   (select  ISNULL(ClientFLAG,1)   from STOREXSDDM where rtrim(BILLID) = @BILLID)


   	 SELECT @SUMAMT= (SELECT SUM(ROUND(DISC*0.01*unitprice*UNITQTY*(1+ISNULL(TAXRATE,0)*0.01),2)) FROM   STOREXSDDD  where rtrim(BILLID) = @BILLID)
   	 SELECT @SUMAMT=0


           IF NOT (exists (select * from ViewCLIENT where CLIENTID=@CLIENTID   and CLIENTFLAG=@CLIENTFLAG))
            BEGIN
			      rollback transaction  trans_XSDD 
			      set @flagreturn = 0
                  SET @RETURNSTRING='客户不能为空或客户不存在，单据不能记帐'
                  RETURN
			END



   update  STOREXSDDM  set  flagPost = 1,YYYYMM =@BILLYYYYMM   ,SUMAMT=VendorHKSum ,INVOICEAMT=0 ,STATUS=0 ,sflag=0        where ltrim(rtrim(BILLID)) = @BILLID 
   update  STOREXSDDD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0),2)    ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)    where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STOREXSDDD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)     where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_XSDD
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_XSDD
      set @flagreturn = 0
   end
end

----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG























----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[STORE_XSDD_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare  @INF_COSTINGTYPEID  INT
declare  @ClientFlag  INT
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @CLIENTID varchar(10)                   --单句会计年月     
declare @VENDORID varchar(10)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @ChaCheSID VARCHAR(25)
declare @INSTOREID    varchar(15)               --明细存货编号

declare @STOREID    varchar(15)               --明细存货编号
declare @REDetailBillFlowID   varchar(30)                     --序列号
declare @REITEMNO   varchar(30)                     --序列号
declare @QUANTITY   NUMERIC(20,10)                     --序列号
declare @STATUS INT
declare @UNITQTY   NUMERIC(20,10)                     --序列号
declare @BILLTYPE   INTEGER
declare @SFLAG   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

                                              SET @RETURNSTRING='   '


	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STOREXSDDM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREXSDDM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_XSDD_DEL   --事物开始

     set @BillType =   (select BillType  from STOREXSDDM where rtrim(BILLID) = @BILLID)
     set @INStoreID =   (select PAYTYPEID  from  STOREXSDDM where rtrim(BILLID) = @BILLID)   ---------收款银行
     set @SFLAG =    (select  ISNULL(SFLAG,0)  from STOREXSDDM where rtrim(BILLID) = @BILLID)
	 set @STATUS =   (select  ISNULL(STATUS,0)  from STOREXSDDM where rtrim(BILLID) = @BILLID)

			IF exists(select   ITEMNO   FROM    STOREXSDDD  where rtrim(BILLID) = @BILLID  AND  ITEMNO  IN (SELECT  REITEMNO   FROM    STOREXSCKD ))
			BEGIN
                              SET @RETURNSTRING=' 此订单已经被销售出库单引用不能取消记帐  '
			      rollback transaction trans_XSDD_DEL
			      set @flagreturn = 0
                                         RETURN
			END


			IF  ( @STATUS=1)  OR  (@SFLAG=1)
             		       BEGIN
                            SET @RETURNSTRING=' 此订单已经完成或终止不能取消记帐！'
			      rollback transaction trans_XSDD_DEL
			      set @flagreturn = 0
                           RETURN
			END

			----如果订单已经被引用则不能取消记帐



   update  STOREXSDDM  set  flagPost = 0 ,STATUS=0 ,sflag=0     where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_XSDD_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_XSDD_DEL
      set @flagreturn = 0
   end
end














----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











CREATE PROCEDURE [dbo].[STORE_XSFP]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---是否现款标志
declare @VENDORFLAG int           ---单据对供应商精确运算标志
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @VENDORID   varchar(15)               --明细存货编号
declare @MakeMan   varchar(15)               --明细存货编号
declare @invoiceCode  varchar(200)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20, 8)                          --数量
declare @SUMAMT NUMERIC(20, 8)                          --单据总金额
declare @REBILLID varchar(15)
declare @REBILLSUMAMT NUMERIC(20,2)                          --引用数量
declare @REBILLDISCAMT NUMERIC(20,2)                          --引用数量
declare @AMT NUMERIC(20,2)                          --引用数量

declare @refqty NUMERIC(20, 8)                          --引用数量
declare @PRICE  NUMERIC(20, 8)               --含税单价
declare @APRICE  NUMERIC(20, 8)               --含税单价
declare @RATE  NUMERIC(20, 8)               --含税单价
declare @BATCHCODE varchar(30)                     --序列号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @UNITID VARCHAR(25)
declare @BILLDATE DATEtime
declare @invoiceDate DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @invoiceFlag  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @PRICEQX   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间


       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

     set @BillDate =   (select BillDate  from STOREXSFPM where rtrim(BILLID) = @BILLID)
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     

      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END

if  (select isnull(flagPost,0) from STOREXSFPM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_XSFP   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREXSFPM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREXSFPM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREXSFPM where rtrim(BILLID) = @BILLID)
     set @MakeMan =   (select MakeMan  from STOREXSFPM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREXSFPM where rtrim(BILLID) = @BILLID)
     set @VENDORID =   (select  VENDOR_CLIENT_ID  from STOREXSFPM where rtrim(BILLID) = @BILLID)
     set @invoiceCode =   (select invoiceCode  from STOREXSFPM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @invoiceDate =   (select invoiceDate  from STOREXSFPM where rtrim(BILLID) = @BILLID)
     set @invoiceFlag =   (select  ISNULL(invoiceFlag,1)  from STOREXSFPM where rtrim(BILLID) = @BILLID)


--------------------------------------------------

----REBILLSUMAMT  单据总额
----REBILLDISCAMT  已开票
----AMT   本次开票

    declare SM_Consign_XSFP Cursor for Select  ITEMNO,REBILLID, REBILLSUMAMT,REBILLDISCAMT,ISNULL(AMT,0) as AMT 
                                                                       from STOREXSFPD where rtrim(BILLID) = @BILLID AND ISNULL(AMT,0)<>0

    Open SM_Consign_XSFP

    fetch SM_Consign_XSFP into @ITEMNO,@REBILLID, @REBILLSUMAMT,@REBILLDISCAMT,@AMT

    while @@fetch_status = 0            ----开始
    begin


	          UPDATE    STOREXSCKM     set    FaPiaoAMT=ISNULL(FaPiaoAMT,0)+@AMT,invoiceCode=ISNULL(invoiceCode,'')+'  '+ISNULL(@invoiceCode,''),
					invoiceDate=@invoiceDate,invoiceFlag=@invoiceFlag
             		           WHERE rtrim(BILLID) = @REBILLID

	  
	          UPDATE    STOREXSCKM     set    STATUS=1
             		           WHERE FaPiaoAMT = SumAMT and YaoPiaoFlag=1


--------------------
    fetch SM_Consign_XSFP into @ITEMNO,@REBILLID, @REBILLSUMAMT,@REBILLDISCAMT,@AMT

    END           ------- SM_Consign_XSFP  WHILE

    close SM_Consign_XSFP
    deallocate SM_Consign_XSFP

-----------------------以上是解决仓库记帐问题，以下是应付帐款的问题
-----------------------------
   update  STOREXSFPM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_XSFP
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_XSFP
      set @flagreturn = 0
   end
end









----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG










CREATE PROCEDURE [dbo].[STORE_XSFP_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @invoiceCode varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @BATCHCODE   varchar(30)                     --序列号
declare @VENDORID   varchar(30)                     --序列号
declare @INF_COSTINGTYPEID   INT
declare @VENDORFLAG   INT
declare @AMT NUMERIC(20,2)                          --引用数量
declare @billtype   INT
declare @SFLAG   INT
declare @REFQTY   NUMERIC(20, 8)
declare @STOREHSFS   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @REBILLSUMAMT NUMERIC(20,2)                          --引用数量
declare @REBILLDISCAMT NUMERIC(20,2)                          --引用数量
declare @invoiceDate DATEtime
declare @invoiceFlag  INTEGER
declare @REBILLID varchar(15)
declare @ITEMNO varchar(15)               --明细存货编号

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDate =  (select BILLDate  from STOREXSFPM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
       IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREXSFPM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_XSFP_DEL   --事物开始

	SELECT @VENDORID=VENDOR_CLIENT_ID    FROM STOREXSFPM  where rtrim(BILLID) = @BILLID 
	     set @BillType =   (select BillType  from STOREXSFPM where rtrim(BILLID) = @BILLID)
     set @invoiceCode =   (select invoiceCode  from STOREXSFPM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @invoiceDate =   (select invoiceDate  from STOREXSFPM where rtrim(BILLID) = @BILLID)
     set @invoiceFlag =   (select  ISNULL(invoiceFlag,1)  from STOREXSFPM where rtrim(BILLID) = @BILLID)



    declare SM_Consign_XSFP_DEL Cursor for Select  ITEMNO,REBILLID, REBILLSUMAMT,REBILLDISCAMT,ISNULL(AMT,0) as AMT 
                                                                       from STOREXSFPD where rtrim(BILLID) = @BILLID AND ISNULL(AMT,0)<>0

    Open SM_Consign_XSFP_DEL

    fetch SM_Consign_XSFP_DEL into @ITEMNO,@REBILLID, @REBILLSUMAMT,@REBILLDISCAMT,@AMT

    while @@fetch_status = 0            ----开始
    begin
	          UPDATE    STOREXSCKM     set    FaPiaoAMT=ISNULL(FaPiaoAMT,0)-@AMT,
			invoiceCode=substring(invoiceCode,1,charindex(@invoiceCode,invoiceCode) -1) + 
			substring(invoiceCode,charindex(@invoiceCode,invoiceCode)+ len(@invoiceCode) ,len(invoiceCode)), 
					invoiceDate=NULL,invoiceFlag=@invoiceFlag
             		           WHERE rtrim(BILLID) = @REBILLID
	  

	          UPDATE    STOREXSCKM     set    STATUS=0
             		           WHERE FaPiaoAMT <> SumAMT and YaoPiaoFlag=1
--------------------
    fetch SM_Consign_XSFP_DEL into @ITEMNO,@REBILLID, @REBILLSUMAMT,@REBILLDISCAMT,@AMT

    END           ------- SM_Consign_XSFP_DEL  WHILE

    close SM_Consign_XSFP_DEL
    deallocate SM_Consign_XSFP_DEL

                             DELETE   DetailBillFlow     WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 AND BILLTYPE=@billtype
--------------------------------------以上上全部删除单据  是解决多次记帐失败的问题

   update  STOREXSFPM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_XSFP_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_XSFP_DEL
      set @flagreturn = 0
   end
end









----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[STORE_XSSK]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @REBILLID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @REBILLTYPE int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。


declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)
declare @SFKTYPE int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)

declare @bill_type int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @BANKID varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @CLIENTID   varchar(15)               --明细存货编号
declare @VendorID   varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @BUMENID varchar(15)               --明细存货编号
declare @qty NUMERIC(20, 8)                          --数量
declare @SUMAMT NUMERIC(20, 8)                          --数量
declare @refqty NUMERIC(20, 8)                          --数量
declare @PRICE  NUMERIC(20, 8)               --含税单价
declare @AMT  NUMERIC(20, 8)               --含税单价
declare @MianAMT  NUMERIC(20, 8)               --含税单价




declare @BILLTYPE INTEGER
declare @ClientFLAG INTEGER

declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @MINBILLDATE DATEtime
declare @MAXBILLDATE DATEtime
declare @PRODUCTDATE DATEtime
declare @B_CODE VARCHAR(25)
declare @V_DATE DATEtime
declare @B_ID INTEGER
declare @STOREHSFS   INTEGER
declare @YYYYMM_FLAG  INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

   declare  @PREV_YYYYMM          varchar(6)  -- 上一个会计年月
   declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @BillDate =   (select BillDate  from STOREXSSKM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END



if  (select isnull(flagPost,0) from STOREXSSKM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_XSSK   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREXSSKM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREXSSKM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREXSSKM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREXSSKM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  SFLAG  from STOREXSSKM where rtrim(BILLID) = @BILLID)
     set @CLIENTID =   (select  VENDOR_CLIENT_ID  from STOREXSSKM where rtrim(BILLID) = @BILLID)
     set @SFKTYPE =   (select  isnull(SFKTYPE,0)  from STOREXSSKM where rtrim(BILLID) = @BILLID)
     set @BANKID =   (select  BANKID  from STORExsskM where rtrim(BILLID) = @BILLID)
     set @ClientFLAG =   (select  ISNULL(ClientFLAG,1)   from STOREXSSKM where rtrim(BILLID) = @BILLID)
     set @BuMenID =   (select  BuMenID  from STOREXSSKM where rtrim(BILLID) = @BILLID)


                                      IF NOT (exists (select * from CLIENT where CLIENTID=@CLIENTID))
                                     BEGIN
			      rollback transaction trans_XSSK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='客户不能为空或客户不存在，单据不能记帐'
                                          RETURN
			END

		IF   @SFKTYPE=0
		begin
			      rollback transaction trans_XSSK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='收款类型不能为空，单据不能记帐'
                                          RETURN
		end

		IF  (@ClientFLAG=0) AND  (@SFKTYPE  IN (5,6))   
		begin

			      rollback transaction trans_CGFK
			      set @flagreturn = 0
                              SET @RETURNSTRING='当客户为供应商核算主体时，收款类型只能选择应收账款，否则单据不能记帐！'
                              RETURN
		END



		IF   @SFKTYPE  IN (4,5)    ---@SFKTYPE =6   为不记录
		begin


                                      IF NOT (exists (select * from BANK where BANKID=@BANKID))
                                     BEGIN
			      rollback transaction trans_XSSK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='银行科目不能为空或银行科目不存在，单据不能记帐'
                                          RETURN
			END
		end
   	 SELECT @SUMAMT= (SELECT AMT  FROM  STOREXSSKM   where rtrim(BILLID) = @BILLID)
   	 SELECT @MianAMT= (SELECT ISNULL(MianAMT,0)  FROM  STOREXSSKM   where rtrim(BILLID) = @BILLID)

	IF  @ClientFLAG=1
	BEGIN

	            IF   (not exists(select *  from CLIENTBILLFLOW  where 
             		                                    (rtrim(CLIENTID) = @CLIENTID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@CLIENTID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@CLIENTID,
		     0,@SUMAMT,Null,
		     -1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
		IF @MianAMT <>0
		Begin
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT ,BuMenID  )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode+'免收金额',@CLIENTID,
		     0,@MianAMT,Null,
		     -1,0 ,@BuMenID )    
		END


                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM

		IF   @SFKTYPE  =6    ---@SFKTYPE =6   为不记录
		BEGIN
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@CLIENTID,
		     0,-@SUMAMT,Null,
		     -1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM

		END

	END
	IF @ClientFLAG=0
	BEGIN

	      SET @VendorID=@ClientID
	            IF   (not exists(select *  from VENDORBILLFLOW  where 
             		                                    (rtrim(VENDORID) = @VENDORID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
	             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,@SUMAMT,Null,
		     1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
		IF @MianAMT <>0
		Begin
	             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode+'免收金额',@VENDORID,
		     0,@MianAMT,Null,
		     1,0  )    
               END      ------IF   END
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM

	END     ----------------   	IF @ClientFLAG=0





------------------------------以下是解决科目帐的算法
	IF   @SFKTYPE  IN (4,5)    ---@SFKTYPE =6   为不记录
	begin
	            IF   (not exists(select *  from BANKBILLFLOW  where 
             		                                    (rtrim(BANKID) = @BANKID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,@SUMAMT,Null,
		     1,0  )    
                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM
	end



    declare SM_Consign_XSSK Cursor for Select  REBILLID, isnull(AMT,0)  as amt ,REBILLTYPE   from STOREXSSKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_XSSK

    fetch SM_Consign_XSSK  into @REBILLID,@AMT,@REBILLTYPE

    while @@fetch_status = 0            ----开始
    begin

		IF @REBILLTYPE=2
		BEGIN
		UPDATE   STOREXSCKM   SET DISCAMT= isnull(DISCAMT,0)+@AMT   WHERE BILLID=@REBILLID 
		END
		IF @REBILLTYPE=-3 
		BEGIN
		UPDATE   CLIENT   SET SURAMT= isnull(SURAMT,0)+@AMT   WHERE CLIENTID=@REBILLID 
		END

	    fetch SM_Consign_XSSK  into @REBILLID,@AMT,@REBILLTYPE

    END

    close SM_Consign_XSSK
    deallocate SM_Consign_XSSK



   update  STOREXSSKM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_XSSK
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_XSSK
      set @flagreturn = 0
   end
end








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














----------------------------------------------------------------------------
CREATE PROCEDURE [dbo].[STORE_XSSK_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @REBILLID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @BANKID    varchar(15)               --明细存货编号
declare @BATCHCODE   varchar(30)                     --序列号
declare @CLIENTID   varchar(30)                     --序列号
declare @INF_COSTINGTYPEID   INT
declare @REBILLTYPE   INT
declare @REFQTY   NUMERIC(20, 8)
declare @AMT NUMERIC(20, 8)
declare @STOREHSFS   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDate =  (select BILLDate  from STOREXSSKM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
       IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREXSSKM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_XSSK_DEL   --事物开始


	     set @CLIENTID =   (select  VENDOR_CLIENT_ID  from STOREXSSKM where rtrim(BILLID) = @BILLID)

	     set @BANKID =   (select  BANKID  from STOREXSSKM where rtrim(BILLID) = @BILLID)
		DELETE   CLIENTBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=4

                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM

		DELETE   BANKBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=4

                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM

    declare SM_Consign_XSSK_DEL Cursor for Select  REBILLID, isnull(AMT,0)  as amt ,REBILLTYPE   from STOREXSSKD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_XSSK_DEL

    fetch SM_Consign_XSSK_DEL  into @REBILLID,@AMT,@REBILLTYPE

    while @@fetch_status = 0            ----开始
    begin

		IF @REBILLTYPE=2
		BEGIN
		UPDATE   STOREXSCKM   SET DISCAMT= isnull(DISCAMT,0)-@AMT   WHERE BILLID=@REBILLID 
		END
		IF @REBILLTYPE=-3 
		BEGIN
		UPDATE   CLIENT   SET SURAMT= isnull(SURAMT,0)-@AMT   WHERE CLIENTID=@REBILLID 
		END

	    fetch SM_Consign_XSSK_DEL  into @REBILLID,@AMT,@REBILLTYPE

    END

    close SM_Consign_XSSK_DEL
    deallocate SM_Consign_XSSK_DEL




   update  STOREXSSKM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_XSSK_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_XSSK_DEL
      set @flagreturn = 0
   end
end






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG


























----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_XSTH]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @BuMenID varchar(10)                   --会计年月     

declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ITEMNO varchar(15)               --明细存货编号
declare @VENDORID varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号、
declare @CLIENTID varchar(15)               --明细存货编号、
declare @SUMAMT  NUMERIC(20,10)               --明细存货编号、
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @INqty NUMERIC(20,10)                          --数量
declare @STOREIDEqty NUMERIC(20,10)                          --仓库数量
declare @REFqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @APRICE  NUMERIC(20,10)               --含税单价
declare @UNITQTY  NUMERIC(20,10)               --含税单价
declare @PRICETYPE  NUMERIC(20,10)               --含税单价
declare @RATE  NUMERIC(20,10)               --含税单价
declare @TAXRATE  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID  varchar(50)
declare @GOODSNAME varchar(30)                     --序列号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BANKID VARCHAR(25)
declare @BILLDATE DATEtime
declare @yyyymm_flag  INTEGER
declare @SFLAG INTEGER
declare @STOREHSFS   INTEGER
declare @NEGCLOSEOFF   bit
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @JianShu [int] 
declare @MeiJianQty [T_QUANTITY] 
declare @LingTou [T_QUANTITY] 

       SELECT    @NEGCLOSEOFF=(SELECT  NEGCLOSEOFF  FROM   ACCINFO    WHERE   GUID='0001' )           

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           


set @BILLID   = ltrim(rtrim(@BILLID))
SET  @RETURNSTRING='  '
   declare  @PREV_YYYYMM          varchar(6)  -- 上一个会计年月
   declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     

     set @BillDate =   (select BillDate  from STOREXSTHM where rtrim(BILLID) = @BILLID)
    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END

if  (select isnull(flagPost,0) from STOREXSTHM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_XSTH   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREXSTHM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREXSTHM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREXSTHM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREXSTHM where rtrim(BILLID) = @BILLID)
     set @CLIENTID =   (select CLIENTID  from STOREXSTHM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREXSTHM where rtrim(BILLID) = @BILLID)
     set @BANKID =   (select BANKID  from  STOREXSTHM where rtrim(BILLID) = @BILLID)   ---------收款银行
     set @BuMenID =   (select BuMenID  from  STOREXSTHM where rtrim(BILLID) = @BILLID)   ---------收款银行


   	 SELECT @SUMAMT= 0



                                      IF NOT (exists (select * from CLIENT where CLIENTID=@CLIENTID))
                                     BEGIN
			      rollback transaction trans_S_SEND
			      set @flagreturn = 0
                                              SET @RETURNSTRING='客户不能为空或客户不存在，单据不能记帐'
                                          RETURN
			END


    declare SM_Consign_XSTH Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(UNITPRICE,0)*ISNULL(DISC,0)*0.01 as PRICE, 
                                                                   REDetailBillFlowID,ISNULL(UNITQTY,0) AS UNITQTY ,PRICETYPE,TAXRATE,JianShu,MeiJianQty,LingTou    from STOREXSTHD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_XSTH

    fetch SM_Consign_XSTH into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY  ,@PRICETYPE,@TAXRATE,@JianShu,@MeiJianQty,@LingTou

    while @@fetch_status = 0            ----开始
    begin

                     set @MeiJianQty =   (select ISNULL(RATE1,0)  from GOODS where  GOODSID = @GOODSID)


                            IF (ISNULL(@JianShu,0)*ISNULL(@MeiJianQty,0)+ISNULL(@LingTou,0)<>@Unitqty) AND (ISNULL(@JianShu,0)<>0 OR ISNULL(@LingTou,0)<>0)
                                     BEGIN
			      rollback transaction trans_XSTH
			      set @flagreturn = 0
                                              SET @RETURNSTRING='件数*每件数量+零头与数量不等，单据不能记帐'
			    close  SM_Consign_XSTH
			    deallocate  SM_Consign_XSTH
                                          RETURN
			END


            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)*0.001  from GOODS where  GOODSID = @GOODSID)

---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
        	IF @UNITQTY=0 
		BEGIN
   		 SELECT @UNITQTY=@QTY/@RATE
		END
	END	


	IF @PRICETYPE=1   
	BEGIN
   	 SELECT @SUMAMT=@SUMAMT+ROUND(@price*@QTY*(1+ISNULL(@TAXRATE,0)*0.01),2)
	END
	IF @PRICETYPE=0  
	BEGIN
   	 SELECT @SUMAMT=@SUMAMT+ROUND(@price*@UNITQTY*(1+ISNULL(@TAXRATE,0)*0.01),2)

		IF   @QTY<>0
		BEGIN
		SET  @PRICE=(@UNITQTY*@PRICE)/@QTY
		END

	END

		SELECT @QTY=0-@QTY    ----是负数
                                        IF NOT (exists (select * from STORE where STOREID=@STOREID))
                                     BEGIN
			      rollback transaction trans_XSTH
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close  SM_Consign_XSTH
			    deallocate  SM_Consign_XSTH
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@STOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_XSTH
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_XSTH
			    deallocate SM_Consign_XSTH
                                          RETURN
			END



            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)

	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@STOREID ,@qty ,@PRICE  ,@REDetailBillFlowID , @BILLID 



                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output
	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT  )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID,-@UNITQTY,
	     @QTY,@price,@StoreID,'F',-1,@QTY*@PRICE,null,
	     0,0 )    
	          UPDATE   STOREXSTHD  set    DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_XSTH

--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END


                      select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID
	          UPDATE     STOREXSTHD     set    APRICE=@APRICE,  DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_XSTH

--------------------
    fetch SM_Consign_XSTH into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY  ,@PRICETYPE,@TAXRATE,@JianShu,@MeiJianQty,@LingTou

    END           ------- SM_Consign_XSTH  WHILE

    close SM_Consign_XSTH
    deallocate SM_Consign_XSTH

   	 SELECT @SUMAMT= 0-@SUMAMT

-------------------
	IF @SFLAG=0
	BEGIN
	            IF   (not exists(select *  from CLIENTBILLFLOW  where 
             		                                    (rtrim(CLIENTID) = @CLIENTID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE, CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode, @CLIENTID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE, CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT ,BuMenID  )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode, @CLIENTID,
		     0,@SUMAMT,Null,
		     1,0  ,@BuMenID)    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM
	END         ---------------IF @SFLAG=0


----------------------
	IF @SFLAG=1  AND  NOT( @BANKID='APSOFT')
	BEGIN

            IF   (not exists(select *  from BANKBILLFLOW  where 
             		                                    (rtrim(BANKID) = @BANKID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,0,Null,
		     @inoutFlag,0  )    
            END      ------IF   END
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,-@SUMAMT,Null,
		     -1,0  )    
                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM
	END     ----------IF @SFLAG=1

   update  STOREXSTHM  set  flagPost = 1,YYYYMM =@BILLYYYYMM , SUMAMT= @SUMAMT ,VendorHKSum=@SUMAMT,INVOICEAMT=0            where ltrim(rtrim(BILLID)) = @BILLID 
---   update  STOREXSCKM  set  flagPost = 1,YYYYMM =@YYYYMM   ,SUMAMT=VendorHKSum ,INVOICEAMT=0          where ltrim(rtrim(BILLID)) = @BILLID 

   update  STOREXSTHD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)          where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STOREXSTHD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)   where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_XSTH
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_XSTH
      set @flagreturn = 0
   end
end













----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG















----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_XSTH_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare  @INF_COSTINGTYPEID  INT
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @CLIENTID varchar(10)                   --单句会计年月     
declare @VENDORID varchar(10)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @REDetailBillFlowID   varchar(30)                     --序列号
declare @BANKID  varchar(30)                     --序列号
declare @QUANTITY   NUMERIC(20,10)                     --序列号
declare @REFQTY NUMERIC(20,10)                     --序列号
declare @BILLTYPE   INTEGER
declare @SFLAG   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

                                              SET @RETURNSTRING='   '


	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STOREXSTHM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREXSTHM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_XSTH_DEL   --事物开始

     set @BillType =   (select BillType  from STOREXSTHM where rtrim(BILLID) = @BILLID)

    declare SM_Consign_XSTH_DEL Cursor for Select GOODSID,DetailBillFlowID,STOREID,REDetailBillFlowID ,QUANTITY    from STOREXSTHD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_XSTH_DEL

    fetch SM_Consign_XSTH_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@REDetailBillFlowID,@QUANTITY

    while @@fetch_status = 0            ----开始
    begin

                             DELETE   DetailBillFlow   WHERE  ID=@DetailBillFlowID
       SELECT  @INF_COSTINGTYPEID = INF_COSTINGTYPEID FROM GOODS WHERE GOODSID=@GOODSID
                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@STOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@STOREID,@YYYYMM
				     END

                            END

--------------------
		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@STOREID AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
        fetch SM_Consign_XSTH_DEL into @GOODSID,@DetailBillFlowID,@STOREID,@REDetailBillFlowID,@QUANTITY

    END           ------- SM_Consign_XSTH_DEL  WHILE

    close SM_Consign_XSTH_DEL
    deallocate SM_Consign_XSTH_DEL

		DELETE    DetailBillFlow    WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@BILLTYPE
------------------------------------以上是删除全部单据明细

	     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREXSTHM where rtrim(BILLID) = @BILLID)
	     set @BANKID =   (select BANKID  from  STOREXSTHM where rtrim(BILLID) = @BILLID)   ---------收款银行
		SELECT @CLIENTID=(SELECT CLIENTID FROM   STOREXSTHM    where ltrim(rtrim(BILLID)) = @BILLID  )

	IF     @SFLAG=0
	BEGIN
		DELETE   CLIENTBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@BILLTYPE
                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM
	END

	IF     @SFLAG=1
	BEGIN
		DELETE   BANKBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@BILLTYPE
                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM
	END




   update  STOREXSTHM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_XSTH_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_XSTH_DEL
      set @flagreturn = 0
   end
end







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG












----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_YYYYMM_INSERT]  
                 (
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。

declare @MINBILLDATE DATEtime
declare @MAXBILLDATE DATEtime

declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)

declare @bill_type int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @BILLID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价

declare @yyYY varchar(4)                      --年
declare @mm varchar(2)                      --月
declare @dd varchar(2)                      --日
declare @idm varchar(8)                     --序列号
declare @idd varchar(8)                     --序列号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @B_CODE VARCHAR(25)
declare @V_DATE DATEtime
declare @B_ID INTEGER
declare @STOREHSFS   INTEGER

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
set @BILLID   = ltrim(rtrim(@BILLID))
   declare  @PREV_YYYYMM          varchar(6)  -- 上一个会计年月
   declare  @Next_YYYYMM          varchar(6)  -- 下一个会计年月

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     

begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_YYYYMM_INSERT   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       

    declare Cursor_YYYYMM_INSERT Cursor for   SELECT DISTINCT GOODSID, STOREID FROM DETAILBILLFLOW
				WHERE (YYYYMMBILL = 1) AND (YYYYMM =  @YYYYMM) 

    Open Cursor_YYYYMM_INSERT

    fetch Cursor_YYYYMM_INSERT into @GOODSID,@STOREID

    while @@fetch_status = 0            ----开始
    begin

            IF NOT (exists (select * from  DETAILBILLFLOW where  GOODSID=@GOODSID AND  STOREID=@STOREID  AND YYYYMMBILL = 0  AND  YYYYMM =@YYYYMM   ))
            BEGIN


	            EXEC  DetailBillFlow_insert_YYYYMM   '000001' ,@GOODSID ,@STOREID ,0 ,0 ,'000001', '000001' 

	END  -------IF NOT (exists (se

    fetch Cursor_YYYYMM_INSERT into @GOODSID,@STOREID

    END           ------- Cursor_YYYYMM_INSERT  WHILE

    close Cursor_YYYYMM_INSERT
    deallocate Cursor_YYYYMM_INSERT


   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_YYYYMM_INSERT
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_YYYYMM_INSERT
      set @flagreturn = 0
   end
end





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













--------------------------------------------------------------------
--------------------------------------------------------------------


--------------------------------------------------------------------

CREATE PROCEDURE [STORE_YunFeiFK]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )    --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @DetailBillFlowID  varchar(8)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG  int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。


declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)

declare @bill_type int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @BANKID varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @VENDORID   varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @DISCAMT NUMERIC(20,10)                          --数量
declare @SUMAMT NUMERIC(20,10)                          --数量
declare @refqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价

declare @BILLTYPE INTEGER

declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @MINBILLDATE DATEtime
declare @MAXBILLDATE DATEtime
declare @PRODUCTDATE DATEtime
declare @B_CODE VARCHAR(25)
declare @V_DATE DATEtime
declare @B_ID INTEGER
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

SET  @RETURNSTRING='  '
set @BILLID   = ltrim(rtrim(@BILLID))

     set @BillDate =   (select BillDate  from STOREYunFeiFKM where rtrim(BILLID) = @BILLID)

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END



if  (select isnull(flagPost,0) from STOREYunFeiFKM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_YunFeiFK   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREYunFeiFKM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREYunFeiFKM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREYunFeiFKM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  SFLAG  from STOREYunFeiFKM where rtrim(BILLID) = @BILLID)
     set @VENDORID =   (select  VENDORID  from STOREYunFeiFKM where rtrim(BILLID) = @BILLID)
     set @BANKID =   (select  BANKID  from STOREYunFeiFKM where rtrim(BILLID) = @BILLID)


                                      IF NOT (exists (select * from YunShuDW where YunShuDWID=@VENDORID))
                                     BEGIN
			      rollback transaction trans_YunFeiFK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='运输单位不能为空或运输单位不存在，单据不能记帐'
                                          RETURN
			END
	IF   NOT( @BANKID='APSOFT')
	begin
                                      IF NOT (exists (select * from BANK where BANKID=@BANKID))
                                     BEGIN
			      rollback transaction trans_YunFeiFK
			      set @flagreturn = 0
                                              SET @RETURNSTRING='银行科目不能为空或银行科目不存在，单据不能记帐'
                                          RETURN
			END
	end
   	 SELECT @DISCAMT= (SELECT DISCAMT  FROM  STOREYunFeiFKM   where rtrim(BILLID) = @BILLID)
   	 SELECT @SUMAMT= (SELECT ISNULL(SUMAMT,0)  FROM  STOREYunFeiFKM   where rtrim(BILLID) = @BILLID)

            IF   (not exists(select *  from YunShuDWBILLFLOW  where 
             		                                    (rtrim(YunShuDWID) = @VENDORID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN
             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,0,Null,
		     @inoutFlag,0  )    
            END      ------IF   END
             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,@DISCAMT,Null,
		     -1,0  )    

		IF @SUMAMT <>0
		Begin

             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode+'调平金额',@VENDORID,
		     0,@SUMAMT,Null,
		     -1,0  )    
		end
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      YunShuDW_CACULATOR_YYYYMM    @VENDORID,@YYYYMM

------------------------------以下是解决科目帐的算法
	IF   NOT( @BANKID='APSOFT')
	begin

            IF   (not exists(select *  from BANKBILLFLOW  where 
             		                                    (rtrim(BANKID) = @BANKID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
            BEGIN
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,0,Null,
		     @inoutFlag,0  )    
            END      ------IF   END
             		    execute  GETKEYVALUE     'BANKBILLFLOW',@R_KeyValue = @NEWID output
		    insert into BANKBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,BANKID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@BANKID,
		     0,@DISCAMT,Null,
		     -1,0  )    
                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM
	end
   update  STOREYunFeiFKM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_YunFeiFK
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_YunFeiFK
      set @flagreturn = 0
   end
end






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG















----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_YunFeiFK_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
 AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @STOREID    varchar(15)               --明细存货编号
declare @BANKID    varchar(15)               --明细存货编号
declare @VENDORID   varchar(30)                     --序列号
declare @INF_COSTINGTYPEID   INT
declare @REFQTY   NUMERIC(20,10)
declare @STOREHSFS   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
                                              SET @RETURNSTRING='   '

	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STOREYunFeiFKM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREYunFeiFKM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_YunFeiFK_DEL   --事物开始


	     set @VENDORID =   (select  VENDORID  from STOREYunFeiFKM where rtrim(BILLID) = @BILLID)

	     set @BANKID =   (select  BANKID  from STOREYunFeiFKM where rtrim(BILLID) = @BILLID)

		DELETE   YunShuDWBILLFLOW   WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=16

                            execute      YunShuDW_CACULATOR_YYYYMM    @VENDORID,@YYYYMM

		DELETE   BANKBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=16

                            execute      BANK_CACULATOR_YYYYMM   @BANKID,@YYYYMM


   update  STOREYunFeiFKM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_YunFeiFK_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_YunFeiFK_DEL
      set @flagreturn = 0
   end
end







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG























----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_ZCD]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @SFLAG    int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @GOODSNAME    varchar(50)               --明细存货编号
declare @STOREIDEqty NUMERIC(20,10)                          --仓库数量
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @INSTOREID varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @RATE NUMERIC(20,10)                          --数量
declare @UNITQTY NUMERIC(20,10)                          --数量
declare @REFqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @APRICE  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID  varchar(50)
declare @OUTSTOREID varchar(15)               --明细存货编号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @MINBILLDATE DATEtime
declare @MAXBILLDATE DATEtime
declare @B_ID INTEGER
declare @PRICETYPE INTEGER
declare @COUNT   INTEGER
declare @NEGCLOSEOFF   bit
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @NEGCLOSEOFF=(SELECT  NEGCLOSEOFF  FROM   ACCINFO    WHERE   GUID='0001' )           

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           
SET  @RETURNSTRING='  '

set @BILLID   = ltrim(rtrim(@BILLID))


     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @BillDate =   (select BillDate  from  STOREZCDM where rtrim(BILLID) = @BILLID)
    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END


if  (select isnull(flagPost,0) from STOREZCDM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_ZCD   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREZCDM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREZCDM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREZCDM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREZCDM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  SFLAG  from STOREZCDM where rtrim(BILLID) = @BILLID)
---     set @INSTOREID  =  (select  VENDORID  from STOREZCDM where rtrim(BILLID) = @BILLID)
--     set @OUTSTOREID  =  (select CLIENTID  from STOREZCDM where rtrim(BILLID) = @BILLID)


    declare SM_Consign_ZCDOUT Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(PRICE,0) as PRICE, 
                                                                   REDetailBillFlowID,Isnull(UNITQTY,0) as UNITQTY,PRICETYPE   from STOREZCDD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_ZCDOUT

    fetch SM_Consign_ZCDOUT into @ITEMNO,@GOODSID,@OUTSTOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY ,@PRICETYPE   

    while @@fetch_status = 0            ----开始
    begin
                                      IF NOT (exists (select * from STORE where STOREID=@OUTSTOREID))
                                     BEGIN
			      rollback transaction trans_ZCD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close SM_Consign_ZCDOUT
			    deallocate SM_Consign_ZCDOUT
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@OUTSTOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_ZCD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_ZCDOUT
			    deallocate SM_Consign_ZCDOUT
                                          RETURN
			END


			declare @FuKuCunOUTQty int    ---1代表数量提示，0代表重量提示
			declare @BiJiaoQTY  NUMERIC(20,10)  ---比较过度用的变量


		        set @FuKuCunOUTQty  = (select optionvalue from accoptions where optionname ='FuKuCunOUTQty')     
		
                        IF    @NEGCLOSEOFF=0 
			BEGIN 
				IF @FuKuCunOUTQty=1
				BEGIN 
	                             	EXEC   GETGOODSIDMEQTY  @OUTSTOREID,@GOODSID,@YYYYMM,@MEQTY=@STOREIDEQTY   OUTPUT
					SET @BiJiaoQTY=@UNITQTY
				END
				ELSE
				BEGIN 
	                             	EXEC   GETGOODSIDEQTY  @OUTSTOREID,@GOODSID,@YYYYMM,@EQTY=@STOREIDEQTY   OUTPUT				
					SET @BiJiaoQTY=@QTY
				END
                                IF @BiJiaoQTY >  ISNULL(@STOREIDEQTY,0)
 		                        BEGIN
                          		                  SET  @GOODSNAME =(SELECT NAME  FROM GOODS WHERE GOODSID=@GOODSID)
				      rollback transaction trans_ZCD
				      set @flagreturn = 0
             		                                 SET @RETURNSTRING='此'+@GOODSNAME+'库存不足不能记帐'
				    close SM_Consign_ZCDOUT
				    deallocate SM_Consign_ZCDOUT
                          		                RETURN
				END
			END
            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)*0.001  from GOODS where  GOODSID = @GOODSID)


---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	



	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@OUTSTOREID ,@qty ,@PRICE ,@REDetailBillFlowID, @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output

	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID,MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT, 
	     REFQTY,REFCOUNT)
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     -@QTY,@price,@OUTStoreID,'F',-1,@QTY*@PRICE,null, 
	    0,0 )    
--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格


                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@OUTSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@OUTSTOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@OUTSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@OUTSTOREID,@YYYYMM
				     END

                            END




-------------------其实三种成本价的核算方式都一样  
--------反填成本单价
		IF   @SFLAG=0   --------反填
		BEGIN
			IF @PRICETYPE=1    ----吨
			BEGIN
		                      select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID
			          UPDATE   STOREZCDD  set  UNITPRICE=@APRICE
             			           WHERE CURRENT OF   SM_Consign_ZCDOUT
			END
			IF @PRICETYPE=0    ----数量
			BEGIN
		                      select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID
			          UPDATE   STOREZCDD  set  UNITPRICE=@APRICE*@QTY/@UNITQTY
             			           WHERE CURRENT OF   SM_Consign_ZCDOUT
			END
		
		END

                  
--------------------
    fetch SM_Consign_ZCDOUT into @ITEMNO,@GOODSID,@OUTSTOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY ,@PRICETYPE   

    END           ------- SM_Consign_ZCDOUT  WHILE

    close SM_Consign_ZCDOUT
    deallocate SM_Consign_ZCDOUT


-----------------------------------------------------以上是出库，以下是入库

    declare SM_Consign_ZCDIN Cursor for Select  ITEMNO,GOODSID,INSTOREID,isnull(QUANTITY,0) as qty,isnull(PRICE,0) as PRICE, 
                                                                   REDetailBillFlowID ,UNITQTY ,PRICETYPE   from STOREZCDD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_ZCDIN

    fetch SM_Consign_ZCDIN into @ITEMNO,@GOODSID,@INSTOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY  ,@PRICETYPE

    while @@fetch_status = 0            ----开始
    begin
                                      IF NOT (exists (select * from STORE where STOREID=@INSTOREID))
                                     BEGIN
			      rollback transaction trans_ZCD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='仓库能为空或仓库不存在，单据不能记帐'
			    close SM_Consign_ZCDIN
			    deallocate SM_Consign_ZCDIN
                                          RETURN
			END


                                      IF exists (select * from STORE where STOREID=@INSTOREID and LIUHFlag=1)
                                     BEGIN
			      rollback transaction trans_ZCD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='除留货单外，其他单据仓库不能为留货仓库，单据不能记帐'
			    close SM_Consign_ZCDIN
			    deallocate SM_Consign_ZCDIN
                                          RETURN
			END



            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
            set @RATE =   (select ISNULL(RATE,0)*0.001  from GOODS where  GOODSID = @GOODSID)


---------------根据理算系数核算重量与数量
	IF @RATE<>0
	Begin
	        IF @QTY=0 
		BEGIN
   		 SELECT @QTY=@RATE*@UNITQTY
		END
	        IF @UNITQTY=0 
		BEGIN
	   	 SELECT @UNITQTY=@QTY/@RATE
		END
	END	


	EXEC  DetailBillFlow_insert_YYYYMM   @ITEMNO ,@GOODSID ,@INSTOREID ,@qty ,@PRICE ,@REDetailBillFlowID,  @BILLID 

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output

	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID, MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,1,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@INStoreID,'F',1,@QTY*@PRICE,null,
	    0,0)    

	          UPDATE   STOREZCDD  set    DetailBillFlowID=@NEWID
             		           WHERE CURRENT OF  SM_Consign_ZCDIN
-----------====================2012-09-04 begin

	IF   @INF_COSTINGTYPEID=6 
	Begin

                 execute  GETKEYVALUE     'DetailBillFlow',@R_KeyValue = @NEWID output

	    insert into DetailBillFlow 
	    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,ITEMNO,GOODSID,
	     INQTY,INPRICE,OUTQTY,OUTPRICE,INF_COSTINGTYPEID, MINQTY,
	     EQTY,EPRICE,STOREID,CACULATEFLAG,INOUTFLAG,EAMOUNT,DIFAMOUNT,
	     REFQTY,REFCOUNT )
	    Values
	    (@NEWID,@BILLYYYYMM,2,@BillDate,@BILLTYPE,@BillID,@BillCode,@itemNo,@GoodsID,
	     @QTY,@price,Null,Null,@INF_COSTINGTYPEID, @UNITQTY,
	     @QTY,@price,@INStoreID,'F',1,@QTY*@PRICE,null,
	    0,0)    
	end
--------------------以上是插入数据到表中，以下是重新核算成本价   本过程只插入数据，不核算成本价格

                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@INSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@INSTOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@INSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
		                        execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@INSTOREID,@YYYYMM
				     END

                            END



		IF   @SFLAG=0   --------反填
		BEGIN
			IF @PRICETYPE=1    ----吨
			BEGIN
		                      select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID
			          UPDATE   STOREZCDD  set  UNITPRICE=@APRICE
             			           WHERE CURRENT OF   SM_Consign_ZCDIN
			END
			IF @PRICETYPE=0    ----数量
			BEGIN
		                      select  @APRICE  = INPRICE    FROM DETAILBILLFLOW   WHERE ID=@NEWID
			          UPDATE   STOREZCDD  set  UNITPRICE=@APRICE*@QTY/@UNITQTY
             			           WHERE CURRENT OF   SM_Consign_ZCDIN
			END
		
		END

    fetch SM_Consign_ZCDIN into @ITEMNO,@GOODSID,@INSTOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY  ,@PRICETYPE

    END           ------- SM_Consign_ZCDIN  WHILE

    close SM_Consign_ZCDIN
    deallocate SM_Consign_ZCDIN


   update  STOREZCDM  set  flagPost = 1,YYYYMM =@BILLYYYYMM            where ltrim(rtrim(BILLID)) = @BILLID 
   update  STOREZCDD  set   AMT  =  Round(ISNULL(quantity,0)*ISNULL(UNITprice,0),2)               where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STOREZCDD  set   AMT  =  Round(ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)            where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_ZCD
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_ZCD
      set @flagreturn = 0
   end
end









----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG


















--------------------------------------------------------------------
----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_ZCD_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   

                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @YYYYMMBILL varchar(6)                   --会计年月   
DECLARE @DetailBillFlowID  varchar(8)                   --会计年月   
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @STOREID    varchar(15)               --明细存货编号
declare @REFQTY   NUMERIC(20,10)

declare @flag_Type int                      --类型(区分，销售1、寄销2、移库3、，4退货，5、采购)

declare @bill_type int           ---单据类型
declare @ITEMNO varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @INSTOREID varchar(15)               --明细存货编号
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @QUANTITY NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID  varchar(50)
declare @OUTSTOREID varchar(15)               --明细存货编号

declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @BILLDATE DATEtime
declare @B_CODE VARCHAR(25)
declare @PRODUCTDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           


                                              SET @RETURNSTRING='   '


set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STOREZCDM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREZCDM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_ZCD_DEL   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREZCDM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREZCDM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREZCDM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREZCDM where rtrim(BILLID) = @BILLID)
--     set @INSTOREID  =  (select CLIENTID  from STOREZCDM where rtrim(BILLID) = @BILLID)
--     set @OUTSTOREID  =  (select VENDORID  from STOREZCDM where rtrim(BILLID) = @BILLID)

    declare SM_Consign_ZCDOUT_DEL Cursor for Select  ITEMNO,GOODSID,STOREID,INSTOREID,REDetailBillFlowID ,QUANTITY ,DetailBillFlowID   from STOREZCDD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_ZCDOUT_DEL

    fetch SM_Consign_ZCDOUT_DEL into @ITEMNO,@GOODSID,@OUTSTOREID,@INSTOREID,@REDetailBillFlowID ,@QUANTITY,@DetailBillFlowID

    while @@fetch_status = 0            ----开始
    begin
	            set @INF_COSTINGTYPEID =   (select INF_COSTINGTYPEID from GOODS where  GOODSID = @GOODSID)
             		  DELETE    DetailBillFlow    WHERE ITEMNO=@ITEMNO  AND BILLID=@BILLID  AND GOODSID=@GOODSID  AND BILLTYPE=205

                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@OUTSTOREID,@YYYYMM
	                             execute      APRICECACULATOR_STORE   @GOODSID,@INSTOREID,@YYYYMM
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@OUTSTOREID,@YYYYMM
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@INSTOREID,@YYYYMM
                            END


                            IF   @STOREHSFS=1    ---分仓库核算
                            BEGIN
	                             execute      APRICECACULATOR_STORE   @GOODSID,@OUTSTOREID,@YYYYMM
	                             execute      APRICECACULATOR_STORE   @GOODSID,@INSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
	                             execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@OUTSTOREID,@YYYYMM
	                             execute      APRICECACULATOR_STORE_XIAN   @GOODSID,@INSTOREID,@YYYYMM
				     END
                            END
                            IF   @STOREHSFS=0
                            BEGIN
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@OUTSTOREID,@YYYYMM
             		                execute      APRICECACULATOR_YYYYMM   @GOODSID,@INSTOREID,@YYYYMM
	                	     IF @INF_COSTINGTYPEID=6
				     BEGIN
             		                execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@OUTSTOREID,@YYYYMM
             		                execute      APRICECACULATOR_YYYYMM_XIAN   @GOODSID,@INSTOREID,@YYYYMM
				     END

                            END


		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@OUTSTOREID  AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM
		 update DetailBillFlow 	set  CACULATEFLAG='T'   WHERE GOODSID=@GOODSID   AND STOREID=@INSTOREID  AND YYYYMMBILL=1  AND   YYYYMM > @YYYYMM

	    fetch SM_Consign_ZCDOUT_DEL into @ITEMNO,@GOODSID,@OUTSTOREID,@INSTOREID,@REDetailBillFlowID ,@QUANTITY,@DetailBillFlowID

    END           ------- SM_Consign_ZCDOUT  WHILE

    close SM_Consign_ZCDOUT_DEL
    deallocate SM_Consign_ZCDOUT_DEL



   update  STOREZCDM  set  flagPost = 0      where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_ZCD_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_ZCD_DEL
      set @flagreturn = 0
   end
end






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG





































----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_ZFD]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 
declare @YYYYMM varchar(6)                   --会计年月     
declare @BuMenID varchar(10)                   --会计年月     
declare @INOUTFLAG int                     --业务类型
declare @INF_COSTINGTYPEID int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ClientFlag int                    ---核算标志，移动加权平均1、个别指定2、全月平均一次3。
declare @ITEMNO varchar(15)               --明细存货编号
declare @YunShuDWID varchar(15)               --明细存货编号
declare @NEWID varchar(15)               --明细存货编号
declare @STOREid varchar(15)               --明细存货编号、
declare @CLIENTID varchar(15)               --明细存货编号、
declare @VENDORID varchar(15)               --明细存货编号、
declare @BANKID varchar(15)               --明细存货编号、
declare @SUMAMT  NUMERIC(20,10)               --明细存货编号、
declare @RATE  NUMERIC(20,10)               --明细存货编号、
declare @goodsid varchar(15)               --明细存货编号
declare @qty NUMERIC(20,10)                          --数量
declare @STOREIDEqty NUMERIC(20,10)                          --仓库数量
declare @REFqty NUMERIC(20,10)                          --数量
declare @UNITqty NUMERIC(20,10)                          --数量
declare @PRICE  NUMERIC(20,10)               --含税单价
declare @PRICETYPE  NUMERIC(20,10)               --含税单价
declare @KEYONGQTY  NUMERIC(20,10)               --含税单价
declare @TAXRATE NUMERIC(20,10)               --含税单价
declare @APRICE  NUMERIC(20,10)               --含税单价
declare @REDetailBillFlowID  varchar(50)
declare @GOODSNAME varchar(30)                     --序列号
declare @BILLTYPE INTEGER
declare @BILLCODE VARCHAR(25)
declare @REITEMNO VARCHAR(25)
declare @BILLDATE DATEtime
declare @SFLAG  INTEGER
declare @YYYYMM_FLAG  INTEGER
declare @count  INTEGER
declare @ChaCheSID VARCHAR(25)
declare @PanYunSID VARCHAR(25)
declare @YunFeiZhiFuFX VARCHAR(25)  ----运费支付方向
declare @ChaChePrice  NUMERIC(20,10)               --含税单价
declare @PanYunPrice  NUMERIC(20,10)               --含税单价
declare @ChaCheSYunfei  NUMERIC(20,10)               --含税单价
declare @PanYunSYunfei  NUMERIC(20,10)               --含税单价
declare @QiTaFeiYong  NUMERIC(20,10)               --含税单价
declare @YunFeiSum  NUMERIC(20,10)               --含税单价
declare @MaxRate  NUMERIC(20,10)               --含税单价
declare @MinRate  NUMERIC(20,10)               --含税单价
declare @DMinSPrice NUMERIC(20,10)               --含税单价

declare @STOREHSFS   INTEGER
declare @ZhongLiangXZ   INTEGER
declare @XSPriceXZ   INTEGER
declare @NEGCLOSEOFF   bit
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间
declare @JianShu [int] 
declare @MeiJianQty [T_QUANTITY] 
declare @LingTou [T_QUANTITY] 


       SELECT    @NEGCLOSEOFF=(SELECT  NEGCLOSEOFF  FROM   ACCINFO    WHERE   GUID='0001' )           

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )  
         


set @BILLID   = ltrim(rtrim(@BILLID))
SET  @RETURNSTRING='  '
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     
     set @ZhongLiangXZ   = (select optionvalue from accoptions where optionname ='ZhongLiangXZ')     
     set @XSPriceXZ   = (select optionvalue from accoptions where optionname ='XSPriceXZ')     

     set @BillDate =   (select BillDate  from STOREZFDM where rtrim(BILLID) = @BILLID)

    EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 


      IF @YYYYMM_FLAG=0
      BEGIN
      SET @RETURNSTRING='此单据日期不在本会计期间内，不能记帐，请重新修改单据日期'
      set @flagreturn = 0
      RETURN
      END


if  (select isnull(flagPost,0) from STOREZFDM where ltrim(rtrim(BILLID)) = @BILLID ) = 1
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_ZFD   --事物开始

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @INOUTFLAG =   (select INOUTFLAG from STOREZFDM where rtrim(BILLID) = @BILLID)
     set @BillCode =   (select CODE from STOREZFDM where rtrim(BILLID) = @BILLID)
     set @BillDate =   (select BillDate  from STOREZFDM where rtrim(BILLID) = @BILLID)
     set @BillType =   (select BillType  from STOREZFDM where rtrim(BILLID) = @BILLID)
     set @CLIENTID =   (select CLIENTID  from STOREZFDM where rtrim(BILLID) = @BILLID)
     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREZFDM where rtrim(BILLID) = @BILLID)
     set @ClientFLAG =   (select  ISNULL(ClientFLAG,1)   from STOREZFDM where rtrim(BILLID) = @BILLID)
     set @BANKID =   (select BANKID  from  STOREZFDM where rtrim(BILLID) = @BILLID)   ---------收款银行
     set @BuMenID =   (select BuMenID  from  STOREZFDM where rtrim(BILLID) = @BILLID)   ---------收款银行

     set @ChaCheSID =   (select ChaCheSID  from STOREZFDM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @PanYunSID =   (select PanYunSID  from STOREZFDM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @YunFeiZhiFuFX =   (select YunFeiZhiFuFX  from STOREZFDM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @ChaChePrice =   (select ISNULL(ChaChePrice,0)  from STOREZFDM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @PanYunPrice =   (select ISNULL(PanYunPrice,0)  from STOREZFDM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @ChaCheSYunFei=    (select ROUND(ISNULL(ChaChePrice,0)*SumQUANTITY,2) from STOREZFDM where rtrim(BILLID) = @BILLID)   ---------付款银行 
     set @PanYunSYunFei=    (select ROUND(ISNULL(PanYunPrice,0)*SumQUANTITY,2) from STOREZFDM where rtrim(BILLID) = @BILLID)   ---------付款银行 
     set @YunFeiSum=   @ChaCheSYunFei+@PanYunSYunFei
     set @QiTaFeiYong =   (select ISNULL(QiTaFeiYong,0)  from STOREZFDM where rtrim(BILLID) = @BILLID)   ---------付款银行


   	 SELECT @SUMAMT= (SELECT SUM(ROUND(DISC*0.01*unitprice*UNITQTY*(1+ISNULL(TAXRATE,0)*0.01),2)) FROM   STOREZFDD  where rtrim(BILLID) = @BILLID)
   	 SELECT @SUMAMT=0

                              IF (NOT exists(select * from YunShuDW where YunShuDWID=@ChaCheSID)) and @ChaChePrice<>0
                              BEGIN
			      rollback transaction trans_CGRK
			      set @flagreturn = 0
                                      SET @RETURNSTRING='叉车商不能为空或叉车商不存在，单据不能记帐'
                                       RETURN
			END

                              IF (NOT exists(select * from YunShuDW where YunShuDWID=@PanYunSID)) and @PanYunPrice<>0
                              BEGIN
			      rollback transaction trans_CGRK
			      set @flagreturn = 0
                                      SET @RETURNSTRING='盘运商不能为空或盘运商不存在，单据不能记帐'
                                       RETURN
			END

                                      IF NOT (exists (select * from ViewCLIENT where CLIENTID=@CLIENTID   and CLIENTFLAG=@CLIENTFLAG))
                                     BEGIN
			      rollback transaction  trans_ZFD 
			      set @flagreturn = 0
                                              SET @RETURNSTRING='客户不能为空或客户不存在，单据不能记帐'
                                          RETURN
			END


                       IF @SFLAG=1 and @ClientFLAG=0
                       BEGIN
			      rollback transaction  trans_ZFD 
			      set @flagreturn = 0
                              SET @RETURNSTRING='当客户为供应商的时候，不允许选择现款销售，单据不能记帐'
                              RETURN
		       END



    declare SM_Consign_ZFD Cursor for Select  ITEMNO,GOODSID,STOREID, isnull(QUANTITY,0) as qty,isnull(UNITPRICE,0)*ISNULL(DISC,0)*0.01 as PRICE, 
                                                                   REDetailBillFlowID,ISNULL(UNITQTY,0) AS UNITQTY  ,PRICETYPE,TAXRATE,JianShu,MeiJianQty,LingTou  from STOREZFDD where rtrim(BILLID) = @BILLID 

    Open SM_Consign_ZFD

    fetch SM_Consign_ZFD into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY,@PRICETYPE,@TAXRATE,@JianShu,@MeiJianQty,@LingTou 

    while @@fetch_status = 0            ----开始
    begin

                     set @MeiJianQty =   (select ISNULL(RATE1,0)  from GOODS where  GOODSID = @GOODSID)


                            IF (ISNULL(@JianShu,0)*ISNULL(@MeiJianQty,0)+ISNULL(@LingTou,0)<>@Unitqty) AND (ISNULL(@JianShu,0)<>0 OR ISNULL(@LingTou,0)<>0)
                                     BEGIN
			      rollback transaction trans_ZFD
			      set @flagreturn = 0
                                              SET @RETURNSTRING='件数*每件数量+零头与数量不等，单据不能记帐'
			    close  SM_Consign_ZFD
			    deallocate  SM_Consign_ZFD
                                          RETURN
			END


    fetch SM_Consign_ZFD into @ITEMNO,@GOODSID,@STOREID,@qty,@PRICE,@REDetailBillFlowID,@UNITQTY,@PRICETYPE,@TAXRATE ,@JianShu,@MeiJianQty,@LingTou


    END           ------- SM_Consign_ZFD  WHILE

    close SM_Consign_ZFD
    deallocate SM_Consign_ZFD

-------------------
-------------------运费结算开始

          IF  @ChaChePrice<>0
	   begin
		set @YunShuDWID=@ChaCheSID
	            IF   (not exists(select *  from YunShuDWBILLFLOW  where 
             		                                    (rtrim(YunShuDWID) = @YunShuDWID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@YunShuDWID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
	             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@YunShuDWID,
		     0,@ChaCheSYunFei,Null,
		     1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      YunShuDW_CACULATOR_YYYYMM   @YunShuDWID,@YYYYMM

	    end

            IF  @PanYunPrice<>0
	    begin
		set @YunShuDWID=@PanYunSID

	            IF   (not exists(select *  from YunShuDWBILLFLOW  where 
             		                                    (rtrim(YunShuDWID) = @YunShuDWID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@YunShuDWID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
	             		    execute  GETKEYVALUE     'YunShuDWBILLFLOW',@R_KeyValue = @NEWID output
		    insert into YunShuDWBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,YunShuDWID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@YunShuDWID,
		     0,@PanYunSYunFei,Null,
		     1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      YunShuDW_CACULATOR_YYYYMM   @YunShuDWID,@YYYYMM

	        end

-------------------运费结算结束
        set @SUMAMT=@SUMAMT+@QiTaFeiYong

        IF @YunFeiZhiFuFX='我方垫付运费' 
        begin
        set @SUMAMT=@SUMAMT+@YunFeiSum
        end


-------------------

	IF @SFLAG=0  and  @ClientFLAG=1
	BEGIN
	            IF   (not exists(select *  from CLIENTBILLFLOW  where 
             		                                    (rtrim(CLIENTID) = @CLIENTID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE, CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode, @CLIENTID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
             		    execute  GETKEYVALUE     'CLIENTBILLFLOW',@R_KeyValue = @NEWID output
		    insert into CLIENTBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE, CLIENTID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT ,BuMenID  )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode, @CLIENTID,
		     0,@SUMAMT,Null,
		     1,0, @BuMenID )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM
	END         ---------------IF @SFLAG=0






	IF @SFLAG=0  and  @ClientFLAG=0
	BEGIN

	      SET @VendorID=@ClientID
	            IF   (not exists(select *  from VENDORBILLFLOW  where 
             		                                    (rtrim(VENDORID) = @VENDORID)
                                        	      and(rtrim(YYYYMM) = @YYYYMM)
	                                              and(rtrim(YYYYMMBILL) = 0)       ---0代表月接记录
             		                                 ) )      
	            BEGIN
             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@YYYYMM,0,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,0,Null,
		     @inoutFlag,0  )    
	            END      ------IF   END
	             		    execute  GETKEYVALUE     'VENDORBILLFLOW',@R_KeyValue = @NEWID output
		    insert into VENDORBILLFLOW 
		    (ID,YYYYMM,YYYYMMBILL,BILLDATE,BILLTYPE,BILLID,BILLCODE,VENDORID,
		     BAMOUNT,INAMOUNT,OUTAMOUNT,
		     INOUTFLAG,EAMOUNT   )
		    Values
		    (@NEWID,@BILLYYYYMM,1,@BillDate,@BillType,@BillID,@BillCode,@VENDORID,
		     0,-@SUMAMT,Null,
		     1,0  )    
-------------------------------增加应收帐款  是 INOUTFLAG为1
                            execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM

	END     ----------------     IF @SFLAG=0


----------------------
   update  STOREZFDM  set  flagPost = 1,YYYYMM =@BILLYYYYMM   ,SUMAMT=VendorHKSum ,INVOICEAMT=0          where ltrim(rtrim(BILLID)) = @BILLID 
   update  STOREZFDD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(quantity,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)          where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=1
   update  STOREZFDD  set   AMT  =  Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0),2)     ,TAXAMT=Round(ISNULL(DISC,100)*0.01*ISNULL(UNITQTY,0)*ISNULL(UNITprice,0)*(100+ISNULL(TAXRATE,0))*0.01,2)   where ltrim(rtrim(BILLID)) = @BILLID   AND PRICETYPE=0
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_ZFD
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_ZFD
      set @flagreturn = 0
   end
end

























----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG




















----------------------------------------------------------------------------
CREATE PROCEDURE [STORE_ZFD_DEL]  
                 (
                  @BILLID varchar(22),      ---单据编号   
                  @RETURNSTRING            varchar(60)    output ,      ---单据编号   
                  @flagreturn int output     ---返回记帐成功  -- 0 不成功  --1 已经取消记帐（或者不是本会计期间的单据，不能取消记帐） --2 本次记帐成功 
                 )   --APSOFTENCRYPTION       WITH ENCRYPTION
AS                 


declare @YYYYMM varchar(6)                   --会计年月     
declare  @INF_COSTINGTYPEID  INT
declare  @ClientFlag  INT
declare @YYYYMMBILL varchar(6)                   --单句会计年月     
declare @CLIENTID varchar(10)                   --单句会计年月     
declare @VENDORID varchar(10)                   --单句会计年月     
declare @goodsid varchar(15)               --明细存货编号
declare @DetailBillFlowID varchar(8)                     --序列号
declare @BANKID varchar(8)                     --序列号
declare @ChaCheSID VARCHAR(25)
declare @PanYunSID VARCHAR(25)

declare @STOREID    varchar(15)               --明细存货编号
declare @REDetailBillFlowID   varchar(30)                     --序列号
declare @REITEMNO   varchar(30)                     --序列号
declare @QUANTITY   NUMERIC(20,10)                     --序列号
declare @UNITQTY   NUMERIC(20,10)                     --序列号
declare @BILLTYPE   INTEGER
declare @SFLAG   INTEGER
declare @BILLDATE DATEtime
declare @YYYYMM_FLAG  INTEGER
declare @STOREHSFS   INTEGER  --分仓核算
declare @BillYYYYMM VARCHAR(10)   ----单据会计期间

       SELECT    @STOREHSFS=(SELECT  STOREHSFS  FROM   ACCINFO    WHERE   GUID='0001' )           

                                              SET @RETURNSTRING='   '


	set @BILLID   = ltrim(rtrim(@BILLID))
     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')       
     set @BILLDATE =   (select BILLDATE  from STOREZFDM where rtrim(BILLID) = @BILLID)
      EXEC  BETWEEN_CURR_YYYYMM  @BILLDATE , @flagreturn=@YYYYMM_FLAG OUTPUT,@BillYYYYMMreturn=@BillYYYYMM OUTPUT  ---返回记帐成功  -- 0 不成功  --1 已经记帐（前后台不以至） --2 本次记帐成功 

      IF @YYYYMM_FLAG=0
       BEGIN
       SET @RETURNSTRING=' 本会计期间以前的单据，不能进行取消记帐  '
       set @flagreturn = 0
       RETURN
       END

if  (select isnull(flagPost,0) from STOREZFDM where ltrim(rtrim(BILLID)) = @BILLID ) = 0
begin --如果已经记帐，则  @flagreturn =1 表示已被其他人取消记帐
     select @flagreturn = 1     
end  
else  
begin
     ----------------------记帐过程开始 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
    begin transaction  trans_ZFD_DEL   --事物开始

     set @BillType =   (select BillType  from STOREZFDM where rtrim(BILLID) = @BILLID)



	     set @SFLAG =   (select  ISNULL(SFLAG,0)  from STOREZFDM where rtrim(BILLID) = @BILLID)
	     set @BANKID =   (select BANKID  from  STOREZFDM where rtrim(BILLID) = @BILLID)   ---------收款银行
		SELECT @CLIENTID=(SELECT CLIENTID FROM   STOREZFDM    where ltrim(rtrim(BILLID)) = @BILLID  )
	     set @CLIENTFLAG =   (select  ISNULL(CLIENTFLAG,1)  from STOREZFDM  where rtrim(BILLID) = @BILLID)



     set @ChaCheSID =   (select ChaCheSID  from STOREZFDM where rtrim(BILLID) = @BILLID)   ---------付款银行
     set @PanYunSID =   (select PanYunSID  from STOREZFDM where rtrim(BILLID) = @BILLID)   ---------付款银行


		DELETE   YunShuDWBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@BILLTYPE
    		         execute      YunShuDW_CACULATOR_YYYYMM   @ChaCheSID,@YYYYMM
    		         execute      YunShuDW_CACULATOR_YYYYMM   @PanYunSID,@YYYYMM


	IF     @SFLAG=0  and @ClientFlag=1
	BEGIN
		DELETE   CLIENTBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@billTYPE
                            execute      CLIENT_CACULATOR_YYYYMM   @CLIENTID,@YYYYMM
	END

		IF @SFLAG=0   and  @ClientFlag=0
		BEGIN

		      SET @VendorID=@ClientID
			DELETE   VENDORBILLFLOW  WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1
							  AND  BILLTYPE=@BILLTYPE
             		               execute      VENDOR_CACULATOR_YYYYMM   @VENDORID,@YYYYMM
	                             DELETE  VENDORBILLFLOW    WHERE  ltrim(rtrim(BILLID)) = @BILLID  AND YYYYMMBILL=1 AND BILLTYPE=@billtype
--------------------------------------以上上全部删除单据  是解决多次记帐失败的问题

		END     




   update  STOREZFDM  set  flagPost = 0    where ltrim(rtrim(BILLID)) = @BILLID 
     

   ----------------------记帐过程结束 成功 则  @flagreturn =2 否则 @flagreturn= 0 -----------------
  if @@error  =  0 --如果无错误  ，提交事物 则  @flagreturn =2  否则 @flagreturn= 0
   begin      commit   transaction trans_ZFD_DEL
      set @flagreturn = 2
   end
   else
   begin
      rollback transaction trans_ZFD_DEL
      set @flagreturn = 0
   end
end











----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG





















--------------------------------------------------------------------
--------------------------------------------------------------------
--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[Store_Yue_JiSuan]
as



Declare 
        @end_dateAddone  datetime,
        @YYYYMM  varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @WHERESTING   varchar(1800),
        @STOREIDSTR   varchar(100),
        @DBSTING   varchar(100)

--@WHERESTR='  and 1=1 '
			SELECT    @WHERESTING  ='     '

			SELECT    @STOREIDSTR   = '     '

     set @YYYYMM   = (select optionvalue from accoptions where optionname ='YYYYMM')     

----------------------------------------------------


                delete Store_GoodsID_YUE
----------------------------------------------------
		SELECT @SQLSTR='	 select  I.GOODSID,       '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)+ isnull(E.INQTY,0)  as EQTY, '   --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.MBQTY,0)+ isnull(E.MINQTY,0)  as UNITQTY '   --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from Goods  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(INQTY*INOUTFLAG)  as INQTY  ,sum(MINQTY*INOUTFLAG)  as MINQTY '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)  +@STOREIDSTR                 --------+@DBSTING  不应该加入
		SELECT @SQLSTR=@SQLSTR+'group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.GOODSID = I.GOODSID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select GOODSID,sum(BQTY) as BQTY ,sum(MBQTY) as MBQTY '
		SELECT @SQLSTR=@SQLSTR+' from DETAILBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) +@STOREIDSTR
		SELECT @SQLSTR=@SQLSTR+' group by GOODSID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.GOODSID = I.GOODSID  '
------------------------以上部分是取当前库存
                          SELECT @SQLSTR=@SQLSTR+'  where     I. GOODSID in (select GOODSID from DETAILBILLFLOW where YYYYMM >='+char(39)+@YYYYMM+char(39)+@STOREIDSTR+')'  + @WHERESTING 
		SELECT @SQLSTR=@SQLSTR+'          order by  I.CODE                '

		INSERT INTO  Store_GoodsID_YUE  EXEC(@SQLSTR)


















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











CREATE PROCEDURE [dbo].[UPDATE_DATA]      --APSOFTENCRYPTION       WITH ENCRYPTION
AS 


BEGIN

declare   @MAXID    varchar(10)

	       UPDATE   GOODS         SET INF_COSTINGTYPEID=1  WHERE    INF_COSTINGTYPEID NOT IN ( 1,2,3,4,5,6)

-----		SELECT  @MAXID=MAX(GOODSID)  FROM GOODS  where Len(GoodsID)=8  and substring(GoodsID,1,3)='000'

--------       UPDATE  KEYVALUETABLE   SET KEYVALUE=@MAXID WHERE   TABLENAME= 'GOODS'  

		declare @flagreturn int 
		exec STORE_YYYYMM_INSERT   @flagreturn output 

	       UPDATE   CLIENT         SET BEGINAMOUNT =0  WHERE   BEGINAMOUNT IS NULL
	       UPDATE   CLIENTBILLFLOW         SET BAMOUNT =0  WHERE  BAMOUNT IS NULL
	       UPDATE   CLIENTBILLFLOW         SET INAMOUNT =0  WHERE  INAMOUNT IS NULL
	       UPDATE   CLIENTBILLFLOW         SET OUTAMOUNT =0  WHERE  OUTAMOUNT IS NULL
	       UPDATE   CLIENTBILLFLOW         SET EAMOUNT =0  WHERE  EAMOUNT IS NULL

	       UPDATE   DETAILBILLFLOW         SET BQTY =0  WHERE  BQTY IS NULL
	       UPDATE   DETAILBILLFLOW         SET BPRICE =0  WHERE  BPRICE  IS NULL
	       UPDATE   DETAILBILLFLOW         SET BAMOUNT =0  WHERE  BAMOUNT IS NULL
	       UPDATE   DETAILBILLFLOW         SET INQTY =0  WHERE  INQTY IS NULL
	       UPDATE   DETAILBILLFLOW         SET INPRICE =0  WHERE  INPRICE  IS NULL
	       UPDATE   DETAILBILLFLOW         SET OUTQTY =0  WHERE  OUTQTY IS NULL
	       UPDATE   DETAILBILLFLOW         SET OUTPRICE =0  WHERE   OUTPRICE  IS NULL
	       UPDATE   DETAILBILLFLOW         SET EQTY =0  WHERE  EQTY IS NULL
	       UPDATE   DETAILBILLFLOW         SET EPRICE =0  WHERE  EPRICE  IS NULL
	       UPDATE   DETAILBILLFLOW         SET EAMOUNT =0  WHERE  EAMOUNT IS NULL

	       UPDATE   DETAILBILLFLOW         SET STOREEQTY =0  WHERE  STOREEQTY IS NULL
	       UPDATE   DETAILBILLFLOW         SET STOREEPRICE =0  WHERE  STOREEPRICE  IS NULL
	       UPDATE   DETAILBILLFLOW         SET STOREEAMOUNT =0  WHERE  STOREEAMOUNT IS NULL

	       UPDATE   DETAILBILLFLOW         SET REFQTY =0  WHERE REFQTY IS NULL
	       UPDATE   DETAILBILLFLOW         SET REFCOUNT =0  WHERE  REFCOUNT  IS NULL

	       UPDATE   GOODSINIT           SET BQTY =0  WHERE  BQTY IS NULL
	       UPDATE   GOODSINIT           SET BPRICE =0  WHERE  BPRICE  IS NULL
	       UPDATE   GOODSINIT           SET BAMOUNT =0  WHERE  BAMOUNT IS NULL
	       UPDATE   GOODSINIT           SET INQTY =0  WHERE  INQTY IS NULL
	       UPDATE   GOODSINIT           SET OUTQTY =0  WHERE  OUTQTY IS NULL
	       UPDATE   GOODSINIT           SET EQTY =0  WHERE  EQTY IS NULL
	       UPDATE   GOODSINIT           SET EPRICE =0  WHERE  EPRICE  IS NULL
	       UPDATE   GOODSINIT           SET EAMOUNT =0  WHERE  EAMOUNT IS NULL

	       UPDATE   STORECGFKM          SET DISCAMT =0  WHERE  DISCAMT  IS NULL
	       UPDATE   STORECGFKM          SET FLAGPOST =0  WHERE  FLAGPOST  IS NULL
	       UPDATE   STORECGFKM          SET INOUTFLAG =-1  WHERE  INOUTFLAG  IS NULL

	       UPDATE   STORECGRKM          SET FLAGPOST =0  WHERE  FLAGPOST  IS NULL
	       UPDATE   STORECGRKM          SET INOUTFLAG =1  WHERE  INOUTFLAG  IS NULL

	       UPDATE   STORECGRKD         SET APRICE =0  WHERE  APRICE  IS NULL
	       UPDATE   STORECGRKD          SET PRICE =0  WHERE  PRICE  IS NULL
	       UPDATE   STORECGRKD          SET QUANTITY =0  WHERE  QUANTITY  IS NULL
	       UPDATE   STORECGRKD          SET TAXRATE =0  WHERE  TAXRATE  IS NULL

	DELETE   VENDORBILLFLOW  WHERE   YYYYMMBILL=1 AND  BILLTYPE=8 AND  (BILLID NOT IN (SELECT BILLID FROM STORECGFKM) )
	DELETE   BANKBILLFLOW  WHERE   YYYYMMBILL=1 AND  BILLTYPE=8 AND  (BILLID NOT IN (SELECT BILLID FROM STORECGFKM) )

	DELETE DetailBillFlow  WHERE   YYYYMMBILL=1  AND  BILLTYPE=1 AND  (BILLID NOT IN (SELECT BILLID FROM STORECGRKM) )
	DELETE VENDORBILLFLOW  WHERE   YYYYMMBILL=1 AND  BILLTYPE=1 AND  (BILLID NOT IN (SELECT BILLID FROM STORECGRKM) )
	DELETE BANKBILLFLOW    WHERE   YYYYMMBILL=1 AND  BILLTYPE=1 AND  (BILLID NOT IN (SELECT BILLID FROM STORECGRKM) )
	DELETE YunShuDWBILLFLOW    WHERE   YYYYMMBILL=1 AND  BILLTYPE=1 AND  (BILLID NOT IN (SELECT BILLID FROM STORECGRKM) )


	DELETE DetailBillFlow  WHERE   YYYYMMBILL=1  AND  BILLTYPE=7 AND  (BILLID NOT IN (SELECT BILLID FROM STORECGTHM) )
	DELETE VENDORBILLFLOW  WHERE   YYYYMMBILL=1 AND  BILLTYPE=7 AND  (BILLID NOT IN (SELECT BILLID FROM STORECGTHM) )
	DELETE BANKBILLFLOW    WHERE   YYYYMMBILL=1 AND  BILLTYPE=7 AND  (BILLID NOT IN (SELECT BILLID FROM STORECGTHM) )

	DELETE DetailBillFlow  WHERE   YYYYMMBILL=1  AND  BILLTYPE=5 AND  (BILLID NOT IN (SELECT BILLID FROM STORECKDBM) )

	DELETE DetailBillFlow  WHERE   YYYYMMBILL=1  AND  BILLTYPE=6 AND  (BILLID NOT IN (SELECT BILLID FROM STORECKPDM) )

	DELETE BANKBILLFLOW    WHERE   YYYYMMBILL=1 AND  BILLTYPE=13 AND  (BILLID NOT IN (SELECT BILLID FROM STOREFYKZM) )
	DELETE DetailBillFlow  WHERE   YYYYMMBILL=1  AND  BILLTYPE=213 AND  (BILLID NOT IN (SELECT BILLID FROM STOREGJRKM) )

	DELETE BANKBILLFLOW    WHERE   YYYYMMBILL=1 AND  BILLTYPE=11 AND  (BILLID NOT IN (SELECT BILLID FROM STOREMOVEM) )

	DELETE DetailBillFlow  WHERE   YYYYMMBILL=1  AND  BILLTYPE=10 AND  (BILLID NOT IN (SELECT BILLID FROM STOREQTCKM ) )
	DELETE DetailBillFlow  WHERE   YYYYMMBILL=1  AND  BILLTYPE=9 AND  (BILLID NOT IN (SELECT BILLID FROM STOREQTRKM ) )

	DELETE BANKBILLFLOW    WHERE   YYYYMMBILL=1 AND  BILLTYPE=3 AND  (BILLID NOT IN (SELECT BILLID FROM STOREQTSRM) )

	DELETE DetailBillFlow  WHERE   YYYYMMBILL=1  AND  BILLTYPE=2 AND  (BILLID NOT IN (SELECT BILLID FROM STOREXSCKM) )
	DELETE CLIENTBILLFLOW  WHERE   YYYYMMBILL=1 AND  BILLTYPE=2 AND  (BILLID NOT IN (SELECT BILLID FROM STOREXSCKM) )
	DELETE BANKBILLFLOW    WHERE   YYYYMMBILL=1 AND  BILLTYPE=2 AND  (BILLID NOT IN (SELECT BILLID FROM STOREXSCKM) )
	DELETE YunShuDWBILLFLOW    WHERE   YYYYMMBILL=1 AND  BILLTYPE=2 AND  (BILLID NOT IN (SELECT BILLID FROM STOREXSCKM) )

	DELETE CLIENTBILLFLOW  WHERE   YYYYMMBILL=1 AND  BILLTYPE=4 AND  (BILLID NOT IN (SELECT BILLID FROM STOREXSSKM) )
	DELETE BANKBILLFLOW    WHERE   YYYYMMBILL=1 AND  BILLTYPE=4 AND  (BILLID NOT IN (SELECT BILLID FROM STOREXSSKM) )

	DELETE DetailBillFlow  WHERE   YYYYMMBILL=1  AND  BILLTYPE=12 AND  (BILLID NOT IN (SELECT BILLID FROM STOREXSTHM) )
	DELETE CLIENTBILLFLOW  WHERE   YYYYMMBILL=1 AND  BILLTYPE=12 AND  (BILLID NOT IN (SELECT BILLID FROM STOREXSTHM) )
	DELETE BANKBILLFLOW    WHERE   YYYYMMBILL=1 AND  BILLTYPE=12 AND  (BILLID NOT IN (SELECT BILLID FROM STOREXSTHM) )

	DELETE DetailBillFlow  WHERE   YYYYMMBILL=1  AND  BILLTYPE=102  AND  (BILLID NOT IN (SELECT BILLID FROM STOREXSDDM) )		
	Update SetCol set ID='888' where ID='999'
END

----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG











--------------------------------------------------------------------
--Create by li fa zheng  2004/05/11             
--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[Update_GoodsTypeNew_fullname] (@LCode varchar(100))   --APSOFTENCRYPTION       WITH ENCRYPTION
AS

--declare local variables needed
declare @PLCode varchar(100)
declare @PPrevno varchar(100)

declare @DIndirect_no varchar(100)
declare @DDirect_no varchar(100)
declare @DSelf_no varchar(100)

declare @CLCode varchar(100)
declare @Name varchar(50)
declare @CPrevno varchar(100)
declare @CPrevPrevno varchar(100)
declare @LongName varchar(200)

declare @temp_no varchar(100)


--find the insert or update record in GoodsTypeNew

----update GoodsTypeNew set fullname= Name  where prevno='0000'
---以上指令时解决顶级的
----本过程是解决非顶级的fullname

select @PLCode=@LCode
    select @Name=Name, @CPrevno=Prevno from GoodsTypeNew where (LCode=@PLCode)
    set @LongName =@Name
--    set @LongName =''

  while exists(select * from GoodsTypeNew where LCode=@CPrevno and LCode<>Prevno )
  begin
    select @Name=Name, @CPrevno=Prevno from GoodsTypeNew where (LCode=@CPrevno)
--	print @Name
--	print @CPrevno
		set @LongName =@Name+'→'+@LongName
  end
---    select @Name=Name, @CPrevno=Prevno from GoodsTypeNew where (LCode=@CPrevno)
--	print @Name
--	print @CPrevno
--		set @LongName =@Name+'→'+@LongName

update   GoodsTypeNew set fullname= @LongName   where LCode=@LCode







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG
















CREATE PROCEDURE [dbo].[Update_GoodsTypeNew_fullname_ALL] 
AS

declare @LCode varchar(100)
declare @SqlSTR varchar(2000)
declare @Step0 int
declare @Step1 int
declare @Step2 int
declare @Step3 int
declare @Step4 int
declare @Step5 int
declare @Step6 int
declare @Step7 int
declare @Step8 int
declare @Step9 int


    update GoodsTypeNew set fullname= Name where prevno='00'


    declare SM_Consign_GoodsTypeNew Cursor for Select  LCode    from GoodsTypeNew where prevno<>'00'

    Open SM_Consign_GoodsTypeNew

    fetch SM_Consign_GoodsTypeNew into @LCode 

    while @@fetch_status = 0            ----开始
    begin

	exec Update_GoodsTypeNew_fullname @LCode

    fetch SM_Consign_GoodsTypeNew into @LCode 

    END           ------- SM_Consign_GoodsTypeNew  WHILE

    close SM_Consign_GoodsTypeNew
    deallocate SM_Consign_GoodsTypeNew















----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG










--------------------------------------------------------------------
--Create by li fa zheng  2004/05/11             
--------------------------------------------------------------------

CREATE PROCEDURE [dbo].[Update_Iteminfo_fullname] (@ItemBM varchar(100))   --APSOFTENCRYPTION       WITH ENCRYPTION
AS

--declare local variables needed
declare @PItemBM varchar(100)
declare @PPrevno varchar(100)

declare @DIndirect_no varchar(100)
declare @DDirect_no varchar(100)
declare @DSelf_no varchar(100)

declare @CItemBM varchar(100)
declare @ItemMC varchar(50)
declare @CPrevno varchar(100)
declare @CPrevPrevno varchar(100)
declare @LongName varchar(200)

declare @temp_no varchar(100)


--find the insert or update record in ItemInfo

----update iteminfo set fullname= itemmc  where prevno='0000'
---以上指令时解决顶级的
----本过程是解决非顶级的fullname

select @PItemBM=@ItemBM
    select @ItemMC=ItemMC, @CPrevno=Prevno from ItemInfo where (ItemBM=@PItemBM)
    set @LongName =@ItemMC
--    set @LongName =''

  while exists(select * from ItemInfo where ItemBM=@CPrevno and ItemBM<>Prevno )
  begin
    select @ItemMC=ItemMC, @CPrevno=Prevno from ItemInfo where (ItemBM=@CPrevno)
--	print @ItemMC
--	print @CPrevno
		set @LongName =@ItemMC+'→'+@LongName
  end
---    select @ItemMC=ItemMC, @CPrevno=Prevno from ItemInfo where (ItemBM=@CPrevno)
--	print @ItemMC
--	print @CPrevno
--		set @LongName =@ItemMC+'→'+@LongName

update   ItemInfo set fullname= @LongName   where ItemBM=@ItemBM






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER ON 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG















CREATE PROCEDURE [dbo].[Update_Iteminfo_fullname_ALL] 
AS

declare @ItemBM varchar(100)
declare @SqlSTR varchar(2000)
declare @Step0 int
declare @Step1 int
declare @Step2 int
declare @Step3 int
declare @Step4 int
declare @Step5 int
declare @Step6 int
declare @Step7 int
declare @Step8 int
declare @Step9 int

---以下指令取得明细科目
---select * from iteminfo where itembm not in (select prevno from iteminfo) 
----
----Select *   from Iteminfo where (itembm = prevno) OR (itembm not in (select prevno from Iteminfo ))
-----取得明细科目 
---    update iteminfo set prevno='0000' where prevno IS NULL
---------

	select @Step0=Step0,@Step1=Step1,@Step2=Step2,@Step3=Step3,@Step4=Step4,@Step5=Step5,@Step6=Step6,@Step7=Step7,
		@Step8=Step8,@Step9=Step9  FROM  ACCINFO  WHERE GUID='0001'

-------------删除不规范科目

---	delete  Iteminfo  where len(ItemBM) NOT in (

	update  Iteminfo set prevno=substring(itembm,1, @Step0)       where len(itembm)=@Step0+@Step1
	update  Iteminfo set prevno=substring(itembm,1, @Step0+@Step1)       where len(itembm)=@Step0+@Step1+@Step2
	update  Iteminfo set prevno=substring(itembm,1, @Step0+@Step1+@Step2)       where len(itembm)=@Step0+@Step1+@Step2+@Step3
	update  Iteminfo set prevno=substring(itembm,1, @Step0+@Step1+@Step2+@Step3)       where len(itembm)=@Step0+@Step1+@Step2+@Step3+@Step4
	update  Iteminfo set prevno=substring(itembm,1, @Step0+@Step1+@Step2+@Step3+@Step4)       where len(itembm)=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5
	update  Iteminfo set prevno=substring(itembm,1, @Step0+@Step1+@Step2+@Step3+@Step4+@Step5)       where len(itembm)=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6
	update  Iteminfo set prevno=substring(itembm,1, @Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6)       where len(itembm)=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7
	update  Iteminfo set prevno=substring(itembm,1, @Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6++@Step7)       where len(itembm)=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7+@Step8
	update  Iteminfo set prevno=substring(itembm,1, @Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6++@Step7+@Step8)       where len(itembm)=@Step0+@Step1+@Step2+@Step3+@Step4+@Step5+@Step6+@Step7+@Step8+@Step9


------先解决明细科目


    update iteminfo set Detailflag=1

    update iteminfo set prevno='0000' where len(itembm)<=4

    update iteminfo set Detailflag=0 where itembm in (select prevno from iteminfo) 

----------------------------
----现金流科目级数2-2-2-3-3  最多5级编码
	set @Step0=2
	set @Step1=2
	set @Step2=2
	set @Step3=3
	set @Step4=3

	update  CW_Cash set prevno=substring(CW_CashID,1, @Step0)       where len(CW_CashID)=@Step0+@Step1
	update  CW_Cash set prevno=substring(CW_CashID,1, @Step0+@Step1)       where len(CW_CashID)=@Step0+@Step1+@Step2
	update  CW_Cash set prevno=substring(CW_CashID,1, @Step0+@Step1+@Step2)       where len(CW_CashID)=@Step0+@Step1+@Step2+@Step3
	update  CW_Cash set prevno=substring(CW_CashID,1, @Step0+@Step1+@Step2+@Step3)       where len(CW_CashID)=@Step0+@Step1+@Step2+@Step3+@Step4

    update CW_Cash set Detailflag=1

    update CW_Cash set prevno='0000' where len(CW_CashID)<=2

    update CW_Cash set Detailflag=0 where CW_CashID in (select prevno from CW_Cash) 


----------------------以上解决明细科目问题

    update iteminfo set fullname= itemmc where prevno='0000'


    declare SM_Consign_Iteminfo Cursor for Select  ItemBM    from Iteminfo where prevno<>'0000'

    Open SM_Consign_Iteminfo

    fetch SM_Consign_Iteminfo into @ItemBM 

    while @@fetch_status = 0            ----开始
    begin

	exec Update_Iteminfo_fullname @ItemBM

    fetch SM_Consign_Iteminfo into @ItemBM 

    END           ------- SM_Consign_Iteminfo  WHILE

    close SM_Consign_Iteminfo
    deallocate SM_Consign_Iteminfo














----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG






--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE [dbo].[VENDORCGDDMXB]( @WHERESTING   varchar(1800)                       
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8)

declare @GOODSNAME  varchar(50)
declare @VENDORNAME  varchar(50)

declare @ID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @VENDORID  nvarchar(50)
declare @GOODSCODE  nvarchar(50)
declare @SpecName  nvarchar(50)
declare @ModelName  nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLCODE  nvarchar(50)
declare @BILLTYPE INT
declare @BILLDATE  datetime
declare @VENDORID00  nvarchar(50)
declare @PRICE NUMERIC(20, 6)
declare @TAXAMT NUMERIC(20, 2)
declare @WCunitQTY NUMERIC(20, 6)
declare @WCquantity NUMERIC(20, 6)
declare @zzunitQTY NUMERIC(20, 6)
declare @zzquantity NUMERIC(20, 6)
declare @WCTAXAMT NUMERIC(20, 6)
declare @TAXRATE  NUMERIC(20, 6)
declare @RATE  NUMERIC(20, 6)
declare @WEITAXAMT NUMERIC(20, 6)
declare @SUMWCTAXAMT NUMERIC(20, 6)
declare @SUMWEITAXAMT NUMERIC(20, 6)
declare @SUMTAXAMT NUMERIC(20, 6)
declare @UNITQTY NUMERIC(20, 6)
declare @quantity NUMERIC(20, 6)
declare @UNITPRICE NUMERIC(20, 6)
declare @DISC NUMERIC(20, 6)
declare    @PRICETYPE int

Create Table #temptable1
      (   VENDORID varchar(50)  NULL,
       GOODSID  varchar(10) ,
       GOODSCODE  varchar(30) ,
      BILLID  nvarchar(50)  NULL,
      BILLTYPE  INT ,
	[PRICE] NUMERIC(20, 6)  NULL ,
	[UNITQTY] NUMERIC(20, 6)  NULL ,
	[quantity] NUMERIC(20, 6)  NULL ,
	[DISC] NUMERIC(20, 6)  NULL ,
	[TAXRATE]NUMERIC(20, 6)  NULL ,
	   BILLDATE  datetime  NULL,
	[UNITPRICE] NUMERIC(20, 6)  NULL ,
	[WCunitQTY]NUMERIC(20, 6)  NULL ,
	[WCquantity]NUMERIC(20, 6)  NULL ,
	[zzunitQTY]NUMERIC(20, 6)  NULL ,
	[zzquantity]NUMERIC(20, 6)  NULL ,
	[TAXAMT]NUMERIC(20, 2)  NULL, 
	[PRICETYPE]    int  NULL, 
	       DETAILBILLFLOWID  varchar(10) 
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   VIEWCGDD.VENDORID,VIEWCGDD.GOODSID,GOODS.CODE AS GOODSCODE, BILLID,BILLTYPE,PRICE,UNITQTY,quantity,DISC,TAXRATE,BILLDATE '
           SELECT  @SQLSTR = @SQLSTR+' ,UNITPRICE,WCunitQTY,WCquantity,zzunitQTY,zzquantity,TAXAMT,PRICETYPE,DETAILBILLFLOWID  from VIEWCGDD   ,GOODS  '  + @WHERESTING +'  AND  VIEWCGDD.GOODSID = GOODS.GOODSID'
           SELECT  @SQLSTR = @SQLSTR+'  order by VIEWCGDD.VENDORID,VIEWCGDD.GOODSID,BILLDATE,DETAILBILLFLOWID '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
	   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   GOODSNAME  nvarchar(50)  NULL,
   GOODSCODE  nvarchar(50)  NULL,
   SpecName  nvarchar(50)  NULL,
   ModelName  nvarchar(50)  NULL,
   UNIT  nvarchar(10)  NULL,
	[UNITQTY] NUMERIC(20, 6)  NULL ,
	[quantity] NUMERIC(20, 6)  NULL ,
	[TAXAMT]NUMERIC(20, 2)  NULL, 
	[WCunitQTY] NUMERIC(20, 6)  NULL ,
	[WCquantity] NUMERIC(20, 6)  NULL ,
	[zzunitQTY] NUMERIC(20, 6)  NULL ,
	[zzquantity] NUMERIC(20, 6)  NULL ,
	[WCTAXAMT]NUMERIC(20, 6)  NULL ,
	[WEIunitQTY] NUMERIC(20, 6)  NULL ,
	[WEIquantity] NUMERIC(20, 6)  NULL ,
	[WEITAXAMT]NUMERIC(20, 6)  NULL 
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (select  VENDORID, GOODSID, BILLID,PRICE,UNITQTY,TAXRATE,BILLTYPE   from  #temptable1        )
                 begin
	    declare CGDDMXB_VENDOR Cursor for select  VENDORID, GOODSID, BILLID,PRICE,UNITQTY,quantity,TAXRATE,BILLTYPE ,DISC,UNITPRICE,WCunitQTY,WCquantity, zzunitQTY,zzquantity,TAXAMT,PRICETYPE  from  #temptable1  
---                                                            ORDER BY  VENDORID,  BILLDATE,DETAILBILLFLOWID,GOODSCODE
                                                            ORDER BY  VENDORID,  BILLDATE,BILLID,GOODSCODE
	    Open CGDDMXB_VENDOR

	    fetch CGDDMXB_VENDOR into   @VENDORID,@GOODSID,@BILLID,@PRICE,@UNITQTY,@quantity,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@WCunitQTY,@WCquantity,@zzunitQTY,@zzquantity,@TAXAMT,@PRICETYPE

                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @VENDORNAME =(SELECT NAME   FROM VENDOR  WHERE VENDORID=@VENDORID)
                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)

                 SELECT  @VENDORID00=@VENDORID

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                                           VALUES  (@COUNTID,@VENDORNAME)
		SELECT @SUMWCTAXAMT=0
		SELECT @SUMTAXAMT=0
		SELECT @SUMWEITAXAMT=0
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF  not( @VENDORID00 = @VENDORID)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,WCTAXAMT,TAXAMT,WEITAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMWCTAXAMT,@SUMTAXAMT,@SUMWEITAXAMT)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @VENDORNAME =(SELECT NAME   FROM VENDOR  WHERE VENDORID=@VENDORID)
		                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @VENDORID00=@VENDORID


			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                           	                VALUES  (@COUNTID,@VENDORNAME)
				SELECT @SUMWCTAXAMT=0
				SELECT @SUMTAXAMT=0
				SELECT @SUMWEITAXAMT=0
		END	
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

				--SELECT @RATE =RATE  FROM GOODSUNIT  WHERE GOODSID=@GOODSID AND UNITID=@UNITID

	  			SELECT @UNIT = (SELECT UNIT   FROM GOODS  WHERE GOODSID=@GOODSID)
				
			   SELECT @BILLCODE=(SELECT CODE   FROM STORECGDDM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STORECGDDM  WHERE BILLID=@BILLID)
               SELECT  @GOODSCODE=CODE,@GOODSNAME=Name,@SpecName=SpecName,@ModelName=ModelName     FROM GOODS  WHERE GOODSID=@GOODSID
	               if @PRICETYPE=1
		               begin  
		                 SET @WEITAXAMT=Round(ISNULL(@DISC,100)*0.01*(ISNULL(@quantity,0)-ISNULL(@WCquantity,0)-ISNULL(@zzquantity,0))*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
		                 SET @WCTAXAMT=Round(ISNULL(@DISC,100)*0.01*ISNULL(@WCquantity,0)*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
					   end
					   else
					   begin
		                 SET @WEITAXAMT=Round(ISNULL(@DISC,100)*0.01*(ISNULL(@unitqty,0)-ISNULL(@WCunitqty,0)-ISNULL(@zzunitqty,0))*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
		                 SET @WCTAXAMT=Round(ISNULL(@DISC,100)*0.01*ISNULL(@WCunitqty,0)*ISNULL(@UNITprice,0)*(100+ISNULL(@TAXRATE,0))*0.01,2)     
					   end
		                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,GOODSNAME,GOODSCODE,SpecName,ModelName,UNIT, UNITQTY,quantity,TAXAMT,WCunitQTY,WCquantity,zzunitQTY,zzquantity,WCTAXAMT,WEIunitQTY,WEIquantity,WEITAXAMT)
             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@GOODSNAME,@GOODSCODE,@SpecName,@ModelName,@UNIT,@UNITQTY,@quantity,
					                     @TAXAMT,
					                     ISNULL(@WCunitQTY,0) ,
					                     ISNULL(@WCquantity,0) ,
					                     ISNULL(@zzunitQTY,0) ,
					                     ISNULL(@zzquantity,0) ,					@WCTAXAMT,
					                      @UNITQTY-ISNULL(@WCunitQTY,0) -ISNULL(@zzunitQTY,0),
					                      @quantity-ISNULL(@WCquantity,0) -ISNULL(@zzquantity,0),@WEITAXAMT	)

				SELECT @SUMTAXAMT=@SUMTAXAMT+@TAXAMT
				SELECT @SUMWCTAXAMT=@SUMWCTAXAMT+@WCTAXAMT
				SELECT @SUMWEITAXAMT=@SUMWEITAXAMT+@WEITAXAMT
		
	    fetch CGDDMXB_VENDOR into   @VENDORID,@GOODSID,@BILLID,@PRICE,@UNITQTY,@quantity,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@WCunitQTY,@WCquantity,@zzunitQTY,@zzquantity,@TAXAMT,@PRICETYPE
 
	    END           ------- CGDDMXB_VENDOR  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,WCTAXAMT,TAXAMT,WEITAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMWCTAXAMT,@SUMTAXAMT,@SUMWEITAXAMT)

	    close CGDDMXB_VENDOR
	    deallocate CGDDMXB_VENDOR
        end     ------------  if exists

 SELECT *  FROM #temptable2         ORDER BY ID











----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE VENDORCGRKMXB( @WHERESTING   varchar(1800)
                      
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8)

declare @GOODSNAME  varchar(50)
declare @VENDORNAME  varchar(50)

declare @ID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @VENDORID  nvarchar(50)
declare @CaiZhi  varchar(50)
declare @ChanDi  varchar(50)
declare @FuzhuQTY  varchar(50)
declare @GOODSCODE  nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLCODE  nvarchar(50)
declare @BILLTYPE INT
declare @PRICETYPE INT
declare @BILLDATE00  datetime
declare @BILLDATE  datetime
declare @VENDORID00  nvarchar(50)
declare @PRICE NUMERIC(20,10)
declare @QUANTITY NUMERIC(20,10)
declare @TAXRATE  NUMERIC(20,10)
declare @SUMAMT NUMERIC(20,10)
declare @SUMTAXAMT NUMERIC(20,10)
declare @SUMDayAMT NUMERIC(20,10)
declare @SUMDayTAXAMT NUMERIC(20,10)
declare @AMT NUMERIC(20,10)
declare @TAXAMT NUMERIC(20,10)
declare @UNITQTY NUMERIC(20,10)
declare @UNITPRICE NUMERIC(20,10)
declare @DISC NUMERIC(20,10)
declare @VendorFlag smallint 
declare @VendorFlag00 smallint 
    

Create Table #temptable1
      (   VENDORID varchar(50)  NULL,
       GOODSID  varchar(10) ,
       GOODSCODE  varchar(30) ,
      BILLID  nvarchar(50)  NULL,
      BILLTYPE  INT ,
	[PRICE] NUMERIC(20,10)  NULL ,
	[QUANTITY] NUMERIC(20,10)  NULL ,
	[DISC] NUMERIC(20,10)  NULL ,
	[TAXRATE]NUMERIC(20,10)  NULL ,
	   BILLDATE  datetime  NULL,
	[UNITPRICE] NUMERIC(20,10)  NULL ,
	[UNITQTY]NUMERIC(20,10)  NULL ,
	       DETAILBILLFLOWID  varchar(10) ,
		     PRICETYPE  INT ,
	[AMT]NUMERIC(20,10)  NULL ,
	[TAXAMT]NUMERIC(20,10)  NULL, 
	[VendorFlag]smallint  NULL ,
       ChanDi  varchar(30) ,
       FuZhuQTY  varchar(30) ,
       CaiZhi  varchar(30) 
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   VIEWCGRK.VENDORID,VIEWCGRK.GOODSID,GOODS.CODE AS GOODSCODE, BILLID,BILLTYPE,PRICE,QUANTITY,DISC,TAXRATE,BILLDATE '
           SELECT  @SQLSTR = @SQLSTR+' ,UNITPRICE,UNITQTY,DETAILBILLFLOWID,PRICETYPE,amt,TAXAMT,VendorFlag,ChanDi,FuzhuQTY,CaiZhi   from VIEWCGRK   ,GOODS  '  + @WHERESTING +'  AND  VIEWCGRK.GOODSID = GOODS.GOODSID'
           SELECT  @SQLSTR = @SQLSTR+'  order by VIEWCGRK.VENDORID,VIEWCGRK.GOODSID,BILLDATE,DETAILBILLFLOWID '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
	   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   GOODSNAME  nvarchar(50)  NULL,
   GOODSCODE  nvarchar(50)  NULL,
   UNIT  nvarchar(10)  NULL,
	[QUANTITY] NUMERIC(20,10)  NULL ,
	[PRICE] NUMERIC(20,10)  NULL ,
	[TAXRATE]NUMERIC(20,10)  NULL ,
	[AMT]NUMERIC(20,10)  NULL ,
	[TAXAMT]NUMERIC(20,10)  NULL ,
	       PRICETYPENAME  varchar(10) ,
       ChanDi  varchar(30) ,
       FuzhuQTY varchar(30) ,
       CaiZhi  varchar(30) 
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (select  VENDORID, GOODSID, BILLID,PRICE,QUANTITY,TAXRATE,BILLTYPE   from  #temptable1        )
                 begin
	    declare CGRKMXB_VENDOR Cursor for select  VENDORID, GOODSID, BILLID,PRICE,QUANTITY,TAXRATE,BILLTYPE ,DISC,UNITPRICE,UNITQTY,PRICETYPE,amt,TAXAMT,VendorFlag,ChanDi,FuzhuQTY,CaiZhi,BILLDATE  from  #temptable1  
                                                            ORDER BY   VENDORID,VendorFlag, BILLDATE,GOODSCODE,DETAILBILLFLOWID
	    Open CGRKMXB_VENDOR

	    fetch CGRKMXB_VENDOR into   @VENDORID,@GOODSID,@BILLID,@PRICE,@QUANTITY,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@UNITQTY,@PRICETYPE,@amt,@TAXAMT,@VendorFlag,@ChanDi,@FuzhuQTY,@CaiZhi,@BILLDATE

                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @VENDORNAME =(SELECT NAME   FROM ViewVENDOR  WHERE VENDORID=@VENDORID  and VendorFlag=@VendorFlag)
                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)

                 SELECT  @VENDORID00=@VENDORID
                 SELECT  @VendorFlag00=@VendorFlag
                 SELECT  @BILLDATE00=@BILLDATE

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                                           VALUES  (@COUNTID,@VENDORNAME)
		SELECT @SUMAMT=0
		SELECT @SUMTAXAMT=0
		SELECT @SUMDayAMT=0
		SELECT @SUMDayTAXAMT=0

	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF  not( @BILLDATE00=@BILLDATE)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,AMT,TAXAMT)
                                           VALUES  (@COUNTID, '按日小计',@SUMDayAMT,@SUMDayTAXAMT)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

----		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
----			         SELECT  @VendorNAME =(SELECT NAME   FROM ViewVendor  WHERE VendorID=@VendorID  and VendorFlag=@VendorFlag)
----		                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @BILLDATE00=@BILLDATE


			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                           	                VALUES  (@COUNTID,@VendorNAME)
				SELECT @SUMDayAMT=0
				SELECT @SUMDayTAXAMT=0
		END	


		IF  not( @VENDORID00 = @VENDORID AND @VendorFlag00=@VendorFlag)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,AMT,TAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMAMT,@SUMTAXAMT)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @VENDORNAME =(SELECT NAME   FROM ViewVENDOR  WHERE VENDORID=@VENDORID  and VendorFlag=@VendorFlag)
		                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @VENDORID00=@VENDORID
		                 SELECT  @VendorFlag00=@VendorFlag

			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                           	                VALUES  (@COUNTID,@VENDORNAME)
				SELECT @SUMAMT=0
				SELECT @SUMTAXAMT=0
				SELECT @SUMDayAMT=0
				SELECT @SUMDayTAXAMT=0

		END	
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
				
			   IF @BILLTYPE=1
			  BEGIN
			   SELECT @BILLCODE=(SELECT CODE   FROM STORECGRKM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STORECGRKM  WHERE BILLID=@BILLID)
			  END
			   IF @BILLTYPE=7
			  BEGIN
			   SELECT @BILLCODE=(SELECT CODE   FROM STORECGTHM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STORECGTHM  WHERE BILLID=@BILLID)
			  END
		                 SELECT  @GOODSNAME=(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @GOODSCODE=(SELECT CODE   FROM GOODS  WHERE GOODSID=@GOODSID)

			   IF @PRICETYPE=1   --吨
			  BEGIN
		                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,GOODSNAME,GOODSCODE,UNIT, QUANTITY,PRICE,TAXRATE, AMT,TAXAMT,PRICETYPENAME,ChanDi,FuzhuQTY,CaiZhi)
             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@GOODSNAME,@GOODSCODE,@UNIT,@QUANTITY,@UNITPRICE,@TAXRATE,@AMT,@TAXAMT,'重量',@ChanDi,@FuzhuQTY,@CaiZhi)
			  END
			   IF @PRICETYPE=0    --
			  BEGIN
		                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,GOODSNAME,GOODSCODE,UNIT, QUANTITY,PRICE,TAXRATE, AMT,TAXAMT,PRICETYPENAME,ChanDi,FuzhuQTY,CaiZhi)
             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@GOODSNAME,@GOODSCODE,@UNIT,@UNITQTY,@UNITPRICE,@TAXRATE,@AMT,@TAXAMT,'数量',@ChanDi,@FuzhuQTY,@CaiZhi)
			  END

				SELECT @SUMAMT=@SUMAMT+@AMT
				SELECT @SUMTAXAMT=@SUMTAXAMT+@TAXAMT
				SELECT @SUMDayAMT=@SUMDayAMT+@AMT
				SELECT @SUMDayTAXAMT=@SUMDayTAXAMT+@TAXAMT
		
	    fetch CGRKMXB_VENDOR into   @VENDORID,@GOODSID,@BILLID,@PRICE,@QUANTITY,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@UNITQTY,@PRICETYPE,@amt,@TAXAMT,@VendorFlag,@ChanDi,@FuzhuQTY,@CaiZhi,@BILLDATE
 
	    END           ------- CGRKMXB_VENDOR  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE,AMT,TAXAMT)
                                           VALUES  (@COUNTID, '小计',@SUMAMT,@SUMTAXAMT)

	    close CGRKMXB_VENDOR
	    deallocate CGRKMXB_VENDOR
        end     ------------  if exists

 SELECT *  FROM #temptable2         ORDER BY ID










----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











--------------------------------------------------------------------
CREATE PROCEDURE VENDORGJRKMXB( 
				@BEGINDATE   varchar(10),
				@ENDDATE   varchar(10),
				@WHERESTING   varchar(1800)
                       
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as

Declare 
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8)

declare @GOODSNAME  varchar(50)
declare @VENDORNAME  varchar(50)

declare @ID  nvarchar(50)
declare @GOODSID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare @VENDORID  nvarchar(50)
declare @GOODSCODE  nvarchar(50)
declare @UNIT  nvarchar(50)
declare @BILLCODE  nvarchar(50)
declare @BILLTYPE INT
declare @BILLDATE  datetime
declare @VENDORID00  nvarchar(50)
declare @PRICE NUMERIC(20,10)
declare @QUANTITY NUMERIC(20,10)
declare @TAXRATE  NUMERIC(20,10)
declare @SUMAMT NUMERIC(20,10)
declare @AMT NUMERIC(20,10)
declare @UNITQTY NUMERIC(20,10)
declare @RETURNQTY NUMERIC(20,10)
declare @UNITPRICE NUMERIC(20,10)
declare @RATE NUMERIC(20,10)
declare @DISC NUMERIC(20,10)
    

Create Table #temptable1
      (   VENDORID varchar(50)  NULL,
       GOODSID  varchar(10) ,
       GOODSCODE  varchar(30) ,
      BILLID  nvarchar(50)  NULL,
      BILLTYPE  INT ,
	[PRICE] NUMERIC(20,10)  NULL ,
	[QUANTITY] NUMERIC(20,10)  NULL ,
	[DISC] NUMERIC(20,10)  NULL ,
	[TAXRATE]NUMERIC(20,10)  NULL ,
	   BILLDATE  datetime  NULL,
	[UNITPRICE] NUMERIC(20,10)  NULL ,
	[UNITQTY]NUMERIC(20,10)  NULL ,
	[RETURNQTY]NUMERIC(20,10)  NULL ,
	       DETAILBILLFLOWID  varchar(10) 
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   VIEWGJRK.VENDORID,VIEWGJRK.GOODSID,GOODS.CODE AS GOODSCODE, BILLID,BILLTYPE,PRICE,QUANTITY,DISC,TAXRATE,BILLDATE '
           SELECT  @SQLSTR = @SQLSTR+' ,UNITPRICE,UNITQTY,RETURNQTY,DETAILBILLFLOWID   from VIEWGJRK   ,GOODS  '  + @WHERESTING +'  AND  VIEWGJRK.GOODSID = GOODS.GOODSID'
           SELECT  @SQLSTR = @SQLSTR+'   AND   BILLDATE <= '+CHAR(39)+@ENDDATE +CHAR(39) +'  AND   BILLDATE >= '+CHAR(39)+@BEGINDATE+CHAR(39)
           SELECT  @SQLSTR = @SQLSTR+'  order by VIEWGJRK.VENDORID,VIEWGJRK.GOODSID,BILLDATE,DETAILBILLFLOWID '  
            EXEC( @SQLSTR)




Create Table #temptable10
      (   VENDORID varchar(50)  NULL,
	[QTY] NUMERIC(20,10)  NULL ,
	[AMT] NUMERIC(20,10)  NULL 
		)

-----------------------------------------这个地方应该为合计数

           SELECT  @SQLSTR = ' INSERT #temptable10  '
           SELECT  @SQLSTR = @SQLSTR+' select  VIEWGJRK.vendoriD,  SUM(ISNULL(QUANTITY,0))  AS QTY '
           SELECT  @SQLSTR = @SQLSTR+' , SUM(UNITPRICE*isnull(quantity,0))  AS AMT      from VIEWGJRK   ,GOODS    '  + @WHERESTING +'  AND  VIEWGJRK.GOODSID = GOODS.GOODSID'
           SELECT  @SQLSTR = @SQLSTR+ ' AND   BILLDATE < '+CHAR(39)+@BEGINDATE +CHAR(39)+'     AND   VIEWGJRK.GOODSID NOT IN (SELECT GOODSID FROM  #temptable1  )   '
---           SELECT  @SQLSTR = @SQLSTR+ ' AND   QUANTITY > 0   AND  ( QUANTITY-ISNULL(RETURNQTY,0)) > 0 '
           SELECT  @SQLSTR = @SQLSTR+'  GROUP  BY  VIEWGJRK.VENDORID   '  
           SELECT  @SQLSTR = @SQLSTR+'  order by  VIEWGJRK.VENDORID  '  
            EXEC( @SQLSTR)



Create Table #temptable2
      (ID  varchar(10) primary key,
	   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   GOODSNAME  nvarchar(50)  NULL,
   GOODSCODE  nvarchar(50)  NULL,
   UNIT  nvarchar(10)  NULL,
	[GRQTY] NUMERIC(20,10)  NULL ,
	[GRAMT] NUMERIC(20,10)  NULL ,
	[CHQTY]NUMERIC(20,10)  NULL ,
	[CHAMT]NUMERIC(20,10)  NULL ,
	[EAMT]NUMERIC(20,10)  NULL 
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (select  VENDORID, GOODSID, BILLID,PRICE,QUANTITY,TAXRATE,BILLTYPE   from  #temptable1        )
                 begin
	    declare GJRKMXB_VENDOR Cursor for select  VENDORID, GOODSID, BILLID,PRICE,QUANTITY,TAXRATE,BILLTYPE ,DISC,UNITPRICE,UNITQTY,RETURNQTY  from  #temptable1  
                                                            ORDER BY   VENDORID,GOODSCODE, BILLDATE,DETAILBILLFLOWID
	    Open GJRKMXB_VENDOR

	    fetch GJRKMXB_VENDOR into   @VENDORID,@GOODSID,@BILLID,@PRICE,@QUANTITY,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@UNITQTY,@RETURNQTY

                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
                 SELECT  @VENDORNAME =(SELECT NAME   FROM VENDOR  WHERE VENDORID=@VENDORID)
                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)

                 SELECT  @VENDORID00=@VENDORID

	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                                           VALUES  (@COUNTID,@VENDORNAME)

		SELECT @SUMAMT=isnull(SUM(QUANTITY*unitPRICE),0)  FROM  VIEWGJRK  WHERE BILLDATE  < @BEGINDATE     AND VENDORID=@VENDORID

		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,EAMT)
                                           VALUES  (@COUNTID, ' 期    初',@SUMAMT)

	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF  not( @VENDORID00 = @VENDORID)
		begin
------------------------------------------------插入空行与小计
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,EAMT)
                                           VALUES  (@COUNTID, '  期   末',@SUMAMT)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)

		                 SELECT  @GOODSNAME =(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @VENDORNAME =(SELECT NAME   FROM VENDOR  WHERE VENDORID=@VENDORID)
		                 SELECT  @GOODSCODE =(SELECT CODE  FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @VENDORID00=@VENDORID


			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                           	                VALUES  (@COUNTID,@VENDORNAME)
				SELECT @SUMAMT=isnull(SUM(QUANTITY*UNITPRICE),0)  FROM  VIEWGJRK  WHERE BILLDATE  < @BEGINDATE  AND VENDORID=@VENDORID
				          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
				          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

			                          INSERT    INTO   #temptable2  (ID, BILLCODE,EAMT)
                          		                 VALUES  (@COUNTID, ' 期    初',@SUMAMT)

		END	
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
	  			SELECT @UNIT = (SELECT UNIT   FROM GOODS  WHERE GOODSID=@GOODSID)
				
			   SELECT @BILLCODE=(SELECT CODE   FROM STOREGJRKM  WHERE BILLID=@BILLID)
			   SELECT @BILLDATE=(SELECT BILLDATE  FROM STOREGJRKM  WHERE BILLID=@BILLID)
		                 SELECT  @GOODSNAME=(SELECT NAME   FROM GOODS  WHERE GOODSID=@GOODSID)
		                 SELECT  @GOODSCODE=(SELECT CODE   FROM GOODS  WHERE GOODSID=@GOODSID)

				SELECT @SUMAMT=@SUMAMT+ROUND(@QUANTITY*@unitPRICE,2)
					IF @QUANTITY>0   
					BEGIN
			                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,GOODSNAME,GOODSCODE,UNIT, GRQTY,GRAMT,EAMT)
	             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@GOODSNAME,@GOODSCODE,@UNIT,@QUANTITY,
						ROUND(@QUANTITY*@UNITPRICE,2),@SUMAMT)
					END

					IF @QUANTITY<0   
					BEGIN
			                          INSERT    INTO   #temptable2  (ID, BILLCODE,BILLDATE,GOODSNAME,GOODSCODE,UNIT, CHQTY,CHAMT,EAMT)
	             		                              VALUES  (@COUNTID,@BILLCODE,@BILLDATE,@GOODSNAME,@GOODSCODE,@UNIT,-@QUANTITY,
						-ROUND(@QUANTITY*@UNITPRICE,2),@SUMAMT)
					END


		
	    fetch GJRKMXB_VENDOR into   @VENDORID,@GOODSID,@BILLID,@PRICE,@QUANTITY,@TAXRATE,@BILLTYPE,@DISC,@UNITPRICE,@UNITQTY,@RETURNQTY
 
	    END           ------- GJRKMXB_VENDOR  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,EAMT)
                                           VALUES  (@COUNTID, '  期   末',@SUMAMT)

	    close GJRKMXB_VENDOR
	    deallocate GJRKMXB_VENDOR
        end     ------------  if exists

-----------------------------------------------------------------------------------------------------------------



	   if exists (select  VENDORID, AMT   from  #temptable10        )
                 begin
	    declare GJRKMXB_SEC_VENDOR Cursor for select  VENDORID,AMT from  #temptable10  
                                                            ORDER BY   VENDORID
	    Open GJRKMXB_SEC_VENDOR

	    fetch GJRKMXB_SEC_VENDOR into   @VENDORID,@sumAMT


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
	                 SELECT  @VENDORNAME =(SELECT NAME   FROM VENDOR  WHERE VENDORID=@VENDORID)
	
             		    SELECT  @VENDORID00=@VENDORID

		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE  )
                                           VALUES  (@COUNTID,@VENDORNAME)

		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,EAMT)
                                           VALUES  (@COUNTID, '  期   初',@SUMAMT)
		          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
		          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

	                          INSERT    INTO   #temptable2  (ID, BILLCODE,EAMT)
                                           VALUES  (@COUNTID, '  期   末',@SUMAMT)
			          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
			          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

		                 INSERT    INTO   #temptable2  (ID)
                                           VALUES  (@COUNTID)


		
	    fetch GJRKMXB_SEC_VENDOR into   @VENDORID,@sumAMT
 
	    END           ------- GJRKMXB_SEC_VENDOR  WHILE
	    close GJRKMXB_SEC_VENDOR
	    deallocate GJRKMXB_SEC_VENDOR
        end     ------------  if exists





 SELECT *  FROM #temptable2         ORDER BY ID





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG











CREATE PROCEDURE VENDORGJRKYYYYMMDD(@Begin_Date   varchar(10) ,
                                                                                           @End_date   varchar(10) ,  
						           @LCODE  varchar(10),             ---如果LCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSCODE  varchar(20),             ---如果GOODSCODE  为‘GGGG’表示不对类别进行查询
						           @GOODSNAME  varchar(20),             ---如果GOODSNAME  为‘GGGG’表示不对类别进行查询
                                                                                           @INF_COSTINGTYPEID   smallint      --------同价调拨标志   0  代表 不作为过滤条件
                       
                                                      )     --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @WHERESTING   varchar(1800)

                   set @now_date=(select   max(billDATE)   FROM  VIEWGJRK)
		
		IF @now_date IS NULL
		BEGIN
			SET @now_date='2030-12-12'
		END

--@WHERESTR='  and 1=1 '
		if     NOT (@LCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = '  AND   I.GOODSID IN ( select G.GOODSID from GoodsTypetree T, GOODS G where T.indirect_no = '+CHAR(39)+@LCODE+CHAR(39)+ '  AND T.self_no=G.LCODE )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  ='     '
 		END
		if     NOT (@GOODSCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  CODE LIKE   '+CHAR(39)+'%'+@GOODSCODE+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  =@WHERESTING+'     '
 		END
		if     NOT (@GOODSNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where  NAME LIKE   '+CHAR(39)+'%'+@GOODSNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END
		if     NOT (@INF_COSTINGTYPEID=0)
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.GOODSID IN ( select  GOODSID from Goods   where INF_COSTINGTYPEID =  '+str(@INF_COSTINGTYPEID)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END

----------------------------------------------------
		SELECT @SQLSTR='	 select  I.VENDORID,       '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0)   as BQTY, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)   as BAMOUNT, ' --期初金额
		SELECT @SQLSTR=@SQLSTR+'ISNULL(BE.INQTY,0)  AS INQTY   ,-ISNULL(BE00.INQTY,0)  AS OUTQTY,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(BE.INAMOUNT,0)  AS INAMOUNT  ,-ISNULL(BE00.INAMOUNT,0)  AS OUTAMOUNT,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BQTY,0) '
		SELECT @SQLSTR=@SQLSTR+'+ isnull(BE.INQTY,0)+isnull(BE00.INQTY,0) as EQTY ,' --期末数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)  '
                           SELECT @SQLSTR=@SQLSTR+'+ISNULL(BE.INAMOUNT,0)+ISNULL(BE00.INAMOUNT,0)       as EAMOUNT '--期初金额
		 SELECT @SQLSTR=@SQLSTR+' from VENDOR  AS  I  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select VENDORID,sum(QUANTITY) as BQTY ,SUM(round(QUANTITY*UNITPRICE,2))  AS BAMOUNT'
		 SELECT @SQLSTR=@SQLSTR+' from VIEWGJRK  '
		SELECT @SQLSTR=@SQLSTR+'  where    BILLDATE < '+char(39)+@begin_date+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by VENDORID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.VENDORID = I.VENDORID  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select VENDORID,sum(QUANTITY) as INQTY  ,sum(round(QUANTITY*UNITPRICE,2))  as INAMOUNT      '
		 SELECT @SQLSTR=@SQLSTR+' from VIEWGJRK  '
		SELECT @SQLSTR=@SQLSTR+' where  QUANTITY > 0  AND BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+@End_Date+char(39)
		SELECT @SQLSTR=@SQLSTR+' group by VENDORID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE on BE.VENDORID = I.VENDORID  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select VENDORID,sum(QUANTITY) as INQTY  ,sum(round(QUANTITY*UNITPRICE,2))  as INAMOUNT      '
		 SELECT @SQLSTR=@SQLSTR+' from VIEWGJRK  '
		SELECT @SQLSTR=@SQLSTR+' where   QUANTITY < 0  AND BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+@End_Date+char(39)
		SELECT @SQLSTR=@SQLSTR+' group by VENDORID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE00 on BE00.VENDORID = I.VENDORID  '
                          SELECT @SQLSTR=@SQLSTR+'  where     I. VENDORID in (select VENDORID from  VIEWGJRK   where    BILLDATE <='+char(39)+@End_Date+char(39)+')'  + @WHERESTING 
		SELECT @SQLSTR=@SQLSTR+'          order by  I.CODE                '   
------------------------------------------------------------------------
		EXEC(@SQLSTR)





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE VENDORINOUTMXBREP(@VENDORID varchar(8) ,                        -----如果为0000则全部仓库
                                                                                            @Begin_Date   varchar(10) ,
                                                                                           @End_date   varchar(10) 
                        
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @end_dateAddone  datetime,
        @MAXBILLDATE  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8),
        @WHERESTING   varchar(1800)

declare @VENDORNAME  varchar(50)
declare @VENDORSTR  varchar(50)

declare @ID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare  @BILLTYPE  INTEGER
declare  @INOUTFLAG  INTEGER
declare @BILLCODE  nvarchar(50)
declare @BILLDATE  datetime
declare @BILLTYPENAME  nvarchar(50)
declare @INAMOUNT NUMERIC(20,10)
declare @OUTAMOUNT NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @EAMOUNTPREV NUMERIC(20,10)
---//==========
declare @BAMOUNT NUMERIC(20,10)
declare @MAXID  nvarchar(50)

                   set @now_date=(select   max(billDATE)   FROM VENDORbillflow )

                          IF @now_date IS NULL
		BEGIN
			set @now_date='2029-10-12'         ----以后纠正此特殊值，此值为调试程序用
		END
                       

                          SELECT    @WHERESTING  = '  AND     BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+ @End_date+char(39) 
                          SELECT    @VENDORSTR  = '  AND     VENDORID ='+char(39)+@VENDORID+char(39)


     

Create Table #temptable10
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL 
		)

Create Table #temptable1
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
    INOUTFLAG  INTEGER
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   ID , BILLID,BILLTYPE,BILLCODE,BILLDATE,BILLTYPE,  '
           SELECT  @SQLSTR = @SQLSTR+'INAMOUNT,OUTAMOUNT,EAMOUNT ,INOUTFLAG '
           SELECT  @SQLSTR = @SQLSTR+'  from VENDORbillflow   where yyyymmbill=1    '  + @WHERESTING+@VENDORSTR 
           SELECT  @SQLSTR = @SQLSTR+'  order by id '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
    INOUTFLAG  INTEGER
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (Select  ID,BILLID,BILLTYPE, BILLCODE,BILLDATE,BILLTYPENAME,
                                                     isnull(INAMOUNT,0) as INAMOUNT ,  isnull(OUTAMOUNT,0) as OUTAMOUNT ,
                                                     isnull(EAMOUNT,0) as EAMOUNT   from  #temptable1        )
                 begin
	    declare INOUTMXBREP Cursor for Select  ID,BILLID,BILLTYPE , BILLCODE,BILLDATE,BILLTYPENAME,
                                                       isnull(INAMOUNT,0) as INAMOUNT ,   isnull(OUTAMOUNT,0) as OUTAMOUNT ,
                                                     isnull(EAMOUNT,0) as EAMOUNT ,INOUTFLAG  from  #temptable1         ORDER BY BILLDATE,ID
	    Open INOUTMXBREP

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INAMOUNT,@OUTAMOUNT,@EAMOUNT,@INOUTFLAG

                 SELECT  @VENDORNAME=NAME   FROM VENDOR  WHERE VENDORID=@VENDORID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME         )
                                           VALUES  (@COUNTID, @VENDORNAME)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                           select @MAXBILLDATE=MAX(BILLDATE) FROM VENDORbillflow   WHERE  VENDORID=@VENDORID   AND     BILLDATE  < @begin_date    AND YYYYMMBILL=1
                           SELECT  @MAXID=MAX(ID)  FROM VENDORbillflow  WHERE  VENDORID=@VENDORID     AND  BILLDATE=@MAXBILLDATE   AND YYYYMMBILL=1
                                         IF @MAXID IS NULL
 			BEGIN
			SET  @BAMOUNT=0
			END
                                        ELSE
			BEGIN
	                           SELECT @BAMOUNT=EAMOUNT   FROM   VENDORbillflow  WHERE ID=@MAXID
			END
                                                              
                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID , '期初结存',@BAMOUNT)
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
                       SELECT  @BILLTYPENAME=NAME FROM  BILLNAME  WHERE @BILLTYPENAME=BILLTYPEID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF @INOUTFLAG=1 
		BEGIN
			SELECT @INAMOUNT=@INAMOUNT
			SELECT @OUTAMOUNT=0
		END
		IF @INOUTFLAG=-1 
		BEGIN
			SELECT @OUTAMOUNT=@INAMOUNT
			SELECT @INAMOUNT=0
		END

                          INSERT    INTO   #temptable2  (ID,BILLID,BILLTYPE, BILLCODE,BILLDATE,BILLTYPENAME,
                                                               INAMOUNT,OUTAMOUNT,EAMOUNT)
                                           VALUES  (@COUNTID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INAMOUNT,@OUTAMOUNT,@EAMOUNT)
 		    SET @EAMOUNTPREV=@EAMOUNT

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INAMOUNT,@OUTAMOUNT,@EAMOUNT,@INOUTFLAG
 

	    END           ------- INOUTMXBREP  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期末结存',@EAMOUNT)

	    close INOUTMXBREP
	    deallocate INOUTMXBREP
        end     ------------  if exists
---------------------------
---------解决当前仓库本期间未发生业务的货品
--                  delete    #temptable1
            ELSE
            BEGIN
                           select @MAXBILLDATE=MAX(BILLDATE) FROM VENDORbillflow   WHERE  VENDORID=@VENDORID   AND     BILLDATE  < @begin_date    AND YYYYMMBILL=1
                           SELECT  @MAXID=MAX(ID)  FROM VENDORbillflow  WHERE  VENDORID=@VENDORID     AND  BILLDATE=@MAXBILLDATE   AND YYYYMMBILL=1

	             	  SELECT    @ID=ID,@EAMOUNT=EAMOUNT    FROM  VENDORbillflow  WHERE    ID =  @MAXID

                 SELECT @VENDORNAME=NAME   FROM VENDOR  WHERE VENDORID=@VENDORID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME         )
                                           VALUES  (@COUNTID,@VENDORNAME)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                                                              
                          INSERT    INTO   #temptable2  (ID , BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期初结存',@EAMOUNT)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期末结存',@EAMOUNT)

---------------------------
	END




--------------------------

 SELECT *  FROM #temptable2         ORDER BY ID






----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG


















CREATE PROCEDURE [dbo].[VENDORYYYYMMDD](  @Begin_Date   varchar(10) ,
                                                                                           @End_date   varchar(10) ,  
                                                                                           @YYYYMM  varchar(8),      --------为当前会计期间
						           @LCODE  varchar(10),             ---如果LCODE  为‘GGGG’表示不对类别进行查询
						           @VENDORCODE  varchar(20),             ---如果VENDORCODE  为‘GGGG’表示不对类别进行查询
						           @VENDORNAME  varchar(20),             ---如果VENDORNAME  为‘GGGG’表示不对类别进行查询
                                                           @ZEROFLAG   smallint      --------  0  代表 不作为过滤条件

                         
                                                      ) as

Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @WHERESTING   varchar(1800)
                   set @now_date=(select   max(billDATE)   FROM  VENDORBILLFLOW)
                          IF @now_date IS NULL
		BEGIN
			set @now_date='2009-12-12'         ----以后纠正此特殊值，此值为调试程序用
		END

		if     NOT (@LCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = '  AND   I.VENDORID IN ( select G.VENDORID from AREAtree T, VENDOR G where T.indirect_no = '+CHAR(39)+@LCODE+CHAR(39)+ '  AND T.self_no=G.AREAID )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  ='     '
 		END
		if     NOT (@VENDORCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.VENDORID IN ( select  VENDORID from VENDOR   where  CODE LIKE   '+CHAR(39)+'%'+@VENDORCODE+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  =@WHERESTING+'     '
 		END
		if     NOT (@VENDORNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.VENDORID IN ( select  VENDORID from VENDOR   where  NAME LIKE   '+CHAR(39)+'%'+@VENDORNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END

--                       print   @WHERESTING
----------------------------------------------------
		SELECT @SQLSTR='	 select  I.VENDORID,  I.CODE,  I.NAME,       '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0) -(isnull(BN.INAMOUNT,0)- isnull(BN00.INAMOUNT,0)) as BAMOUNT, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(BE.INAMOUNT,0)  AS INAMOUNT   ,ISNULL(BE00.INAMOUNT,0)  AS OUTAMOUNT,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0) -(isnull(BN.INAMOUNT,0)- isnull(BN00.INAMOUNT,0))'
		SELECT @SQLSTR=@SQLSTR+'+ isnull(BE.INAMOUNT,0)-isnull(BE00.INAMOUNT,0) as EAMOUNT' --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from VENDOR  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select VENDORID,sum(INAMOUNT*INOUTFLAG)  as INAMOUNT  '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from VENDORBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)
		SELECT @SQLSTR=@SQLSTR+'group by VENDORID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.VENDORID = I.VENDORID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select VENDORID,sum(BAMOUNT) as BAMOUNT '
		SELECT @SQLSTR=@SQLSTR+' from VENDORBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by VENDORID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.VENDORID = I.VENDORID  '
------------------------以上部分是取当前库存
		SELECT @SQLSTR=@SQLSTR+'  left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select VENDORID,sum(INAMOUNT) as INAMOUNT      '
		SELECT @SQLSTR=@SQLSTR+'  from VENDORBILLFLOW           '
		SELECT @SQLSTR=@SQLSTR+'  where YYYYMMBILL = 1    and BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+ @Now_Date+char(39) +'  AND INOUTFLAG =1'   
		SELECT @SQLSTR=@SQLSTR+' group by VENDORID'	
		SELECT @SQLSTR=@SQLSTR+' ) as BN on BN.VENDORID = I.VENDORID'  
		SELECT @SQLSTR=@SQLSTR+'  left outer join '
		SELECT @SQLSTR=@SQLSTR+'  (  '
		SELECT @SQLSTR=@SQLSTR+'select VENDORID,sum(INAMOUNT) as INAMOUNT     '
		SELECT @SQLSTR=@SQLSTR+' from VENDORBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+ @Now_Date +char(39) +' AND INOUTFLAG =-1 '  
		SELECT @SQLSTR=@SQLSTR+' group by VENDORID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BN00 on BN00.VENDORID = I.VENDORID  '
------------------------以上部分为取begin_date到Now_Date的库存
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select VENDORID,sum(INAMOUNT) as INAMOUNT   '
		SELECT @SQLSTR=@SQLSTR+' from VENDORBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+@End_Date+char(39)+' AND INOUTFLAG =1 '  
		SELECT @SQLSTR=@SQLSTR+' group by VENDORID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE on BE.VENDORID = I.VENDORID  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select VENDORID,sum(INAMOUNT) as INAMOUNT   '
		SELECT @SQLSTR=@SQLSTR+' from VENDORBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+@End_Date +char(39)+'AND INOUTFLAG =-1' 
		SELECT @SQLSTR=@SQLSTR+' group by VENDORID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE00 on BE00.VENDORID = I.VENDORID  '
                          SELECT @SQLSTR=@SQLSTR+'  where     I. VENDORID in (select VENDORID from VENDORBILLFLOW where YYYYMM >='+char(39)+@YYYYMM+char(39)+')'  + @WHERESTING 
	             SELECT @SQLSTR=@SQLSTR+'          order by  I.VENDORID                '    
------------------------------------------------------------------------
--		       print   @SQLSTR

Create Table #temptable2012YF
      (VENDORID  varchar(10) primary key,
	    CODE  varchar(100) ,
	    NAME  varchar(100) ,
	  BAMOUNT NUMERIC(20,10)  NULL, 
	  INAMOUNT NUMERIC(20,10)  NULL, 
	  OUTAMOUNT NUMERIC(20,10)  NULL, 
	   EAMOUNT NUMERIC(20,10)  NULL 
		)

		INSERT INTO  #temptable2012YF  EXEC(@SQLSTR)


		IF  @ZEROFLAG=0
		BEGIN
                     SELECT *  FROM  #temptable2012YF
		END
		IF  @ZEROFLAG=1
		BEGIN
                     SELECT *  FROM  #temptable2012YF  where EAMOUNT<>0
		END














----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













CREATE PROCEDURE [VENDOR_CACULATOR_YYYYMM ]  (
	@VENDORID  varchar(30),
	@YYYYMM  varchar(6)    )
AS 
 
declare @INOUTFLAG NUMERIC(20,10)
declare @INAMOUNT  NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @SUMBAMOUNT NUMERIC(20,10)            ---本期期初总金额
 
BEGIN

            select    @SUMBAMOUNT=isnull(BAMOUNT,0)   FROM   VENDORBILLFlow  where    (rtrim(VENDORID) = @VENDORID) 
						  and (rtrim(YYYYMM) = @YYYYMM) 	and   ( YYYYMMBILL=0   )  
                                       -------以上是期初数据
----------------------------------------------------------------
	    declare VENDOR_CACULATOR Cursor for Select  VENDORID , isnull(INAMOUNT,0) as INAMOUNT, INOUTFLAG, isnull(EAMOUNT,0) as EAMOUNT 
	                  from VENDORBILLFlow   where (rtrim(YYYYMM) >= @YYYYMM)  AND ( VENDORID=@VENDORID)   and   ( YYYYMMBILL=1   )  
             		      ORDER BY BILLDATE,ID

	    Open VENDOR_CACULATOR

	    fetch VENDOR_CACULATOR into @VENDORID,@INAMOUNT,@INOUTFLAG,@EAMOUNT


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
		 select    @SUMBAMOUNT=@SUMBAMOUNT+@INAMOUNT*@INOUTFLAG

	         	 UPDATE   VENDORBILLFLOW  set   EAMOUNT=@SUMBAMOUNT      WHERE CURRENT OF  VENDOR_CACULATOR

		    fetch VENDOR_CACULATOR into @VENDORID,@INAMOUNT,@INOUTFLAG,@EAMOUNT
 
	    END           ------- VENDOR_CACULATOR  WHILE

	    close VENDOR_CACULATOR
	    deallocate VENDOR_CACULATOR

-----------------------------------------------------------------------------------------------------------------------------------------------------------


END









----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG















--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE YYYYMMPOSTBILL(  @YYYYMM varchar(8)   )   --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @end_dateAddone  datetime,
        @BILLDATE  datetime,
        @SQLSTR   varchar(8000)


declare @ID  nvarchar(50)
declare @NEWID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare  @BILLTYPE  INTEGER
declare @BILLCODE  nvarchar(50)
declare @SPECNAME  nvarchar(50)


Create Table #temptable888
      (ID  varchar(10)  NULL,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL
		)

Create Table #temptable999 
      (ID  varchar(10)  NULL,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL
		)

		           SELECT  @SQLSTR = ' INSERT #temptable888    '
		           SELECT  @SQLSTR = @SQLSTR+'  select  distinct   id,billid,billtype,billcode,billdate   from   DETAILBILLFLOW  '
		           SELECT  @SQLSTR = @SQLSTR+'  where billid is not null  and yyyymmbill=1 and  yyyymm =  '
		           SELECT  @SQLSTR = @SQLSTR+char(39)+@yyyymm+char(39)
		           SELECT  @SQLSTR = @SQLSTR+'   order by billdate ,id '
		            EXEC( @SQLSTR)

		           SELECT  @SQLSTR = ' INSERT #temptable999   '
		           SELECT  @SQLSTR = @SQLSTR+'  select  distinct   0001  AS  ID, billid,billtype,billcode,billdate    from   DETAILBILLFLOW  '
		           SELECT  @SQLSTR = @SQLSTR+'  where billid is not null  and yyyymmbill=1 and  yyyymm =  '
		           SELECT  @SQLSTR = @SQLSTR+char(39)+@yyyymm+char(39)
		           SELECT  @SQLSTR = @SQLSTR+'   order by billdate  '

		            EXEC( @SQLSTR)
			
	    declare SM_Consign_POSTBILL Cursor for  select    id,billid,billtype,billcode,billdate   from  #temptable999 

	    Open SM_Consign_POSTBILL

	    fetch SM_Consign_POSTBILL into @ID ,@billid,@billtype,@billcode,@billdate

	    while @@fetch_status = 0            ----开始
	    begin
			SELECT @NEWID =(SELECT  MAX(ID)  FROM #temptable888  WHERE BILLID=@billid   AND BILLTYPE=@billTYPE   )


		          UPDATE   #temptable999  set    ID=@NEWID
             			           WHERE CURRENT OF SM_Consign_POSTBILL

	    fetch SM_Consign_POSTBILL into @ID ,@billid,@billtype,@billcode,@billdate

	    END           ------- SM_Consign_POSTBILL  WHILE

	    close SM_Consign_POSTBILL
	    deallocate SM_Consign_POSTBILL

           
 SELECT  AA.id,AA.billid,AA.billtype,AA.billcode,AA.billdate,BB.VENDORID,BB.CLIENTID,BB.POSTMAN,BB.MAKEMAN ,BB.OLDBILLCODE,BB.MEMO,BB.EMPID,BB.BUMENID   FROM #temptable999   AS  AA ,VIEWBILL   AS BB
 WHERE  AA.BILLID= BB.BILLID AND   AA.BILLTYPE= BB.BILLTYPE        ORDER BY  aa.billdate, ID





----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG















--------------------------------------------------------------------
--------------------------------------------------------------------
CREATE PROCEDURE YunShuDWINOUTMXBREP(@YunShuDWID varchar(8) ,                        -----如果为0000则全部仓库
                                                                                            @Begin_Date   varchar(10) ,
                                                                                           @End_date   varchar(10) 
                        
                                                      )      --APSOFTENCRYPTION       WITH ENCRYPTION
as


Declare 
        @end_dateAddone  datetime,
        @MAXBILLDATE  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @COUNTID   varchar(8),
        @WHERESTING   varchar(1800)

declare @YunShuDWNAME  varchar(50)
declare @YunShuDWSTR  varchar(50)

declare @ID  nvarchar(50)
declare @BILLID  nvarchar(50)
declare  @BILLTYPE  INTEGER
declare  @INOUTFLAG  INTEGER
declare @BILLCODE  nvarchar(50)
declare @BILLDATE  datetime
declare @BILLTYPENAME  nvarchar(50)
declare @INAMOUNT NUMERIC(20,10)
declare @OUTAMOUNT NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @EAMOUNTPREV NUMERIC(20,10)
---//==========
declare @BAMOUNT NUMERIC(20,10)
declare @MAXID  nvarchar(50)

                   set @now_date=(select   max(billDATE)   FROM YunShuDWbillflow )

                          IF @now_date IS NULL
		BEGIN
			set @now_date='2029-10-12'         ----以后纠正此特殊值，此值为调试程序用
		END
                       

                          SELECT    @WHERESTING  = '  AND     BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+ @End_date+char(39) 
                          SELECT    @YunShuDWSTR  = '  AND     YunShuDWID ='+char(39)+@YunShuDWID+char(39)


     

Create Table #temptable10
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL 
		)

Create Table #temptable1
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
    INOUTFLAG  INTEGER
		)


           SELECT  @SQLSTR = ' INSERT #temptable1  '
           SELECT  @SQLSTR = @SQLSTR+' select   ID , BILLID,BILLTYPE,BILLCODE,BILLDATE,BILLTYPE,  '
           SELECT  @SQLSTR = @SQLSTR+'INAMOUNT,OUTAMOUNT,EAMOUNT ,INOUTFLAG '
           SELECT  @SQLSTR = @SQLSTR+'  from YunShuDWbillflow   where yyyymmbill=1    '  + @WHERESTING+@YunShuDWSTR 
           SELECT  @SQLSTR = @SQLSTR+'  order by id '  
            EXEC( @SQLSTR)


Create Table #temptable2
      (ID  varchar(10) primary key,
   BILLID  nvarchar(50)  NULL,
   BILLTYPE  INTEGER,
   BILLCODE  nvarchar(50)  NULL,
   BILLDATE  datetime  NULL,
   BILLTYPENAME  nvarchar(50)  NULL,
	[INAMOUNT] NUMERIC(20,10)  NULL ,
	[OUTAMOUNT] NUMERIC(20,10)  NULL ,
	[EAMOUNT]NUMERIC(20,10)  NULL ,
    INOUTFLAG  INTEGER
		)


---------------------------------------------------
	          set @COUNTID='00000001'
	   if exists (Select  ID,BILLID,BILLTYPE, BILLCODE,BILLDATE,BILLTYPENAME,
                                                     isnull(INAMOUNT,0) as INAMOUNT ,  isnull(OUTAMOUNT,0) as OUTAMOUNT ,
                                                     isnull(EAMOUNT,0) as EAMOUNT   from  #temptable1        )
                 begin
	    declare INOUTMXBREP Cursor for Select  ID,BILLID,BILLTYPE , BILLCODE,BILLDATE,BILLTYPENAME,
                                                       isnull(INAMOUNT,0) as INAMOUNT ,   isnull(OUTAMOUNT,0) as OUTAMOUNT ,
                                                     isnull(EAMOUNT,0) as EAMOUNT ,INOUTFLAG  from  #temptable1         ORDER BY BILLDATE,ID
	    Open INOUTMXBREP

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INAMOUNT,@OUTAMOUNT,@EAMOUNT,@INOUTFLAG

                 SELECT  @YunShuDWNAME=YunShuDWNAME   FROM YunShuDW  WHERE YunShuDWID=@YunShuDWID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME         )
                                           VALUES  (@COUNTID, @YunShuDWNAME)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                           select @MAXBILLDATE=MAX(BILLDATE) FROM YunShuDWbillflow   WHERE  YunShuDWID=@YunShuDWID   AND     BILLDATE  < @begin_date    AND YYYYMMBILL=1
                           SELECT  @MAXID=MAX(ID)  FROM YunShuDWbillflow  WHERE  YunShuDWID=@YunShuDWID     AND  BILLDATE=@MAXBILLDATE   AND YYYYMMBILL=1
                                         IF @MAXID IS NULL
 			BEGIN
			SET  @BAMOUNT=0
			END
                                        ELSE
			BEGIN
	                           SELECT @BAMOUNT=EAMOUNT   FROM   YunShuDWbillflow  WHERE ID=@MAXID
			END
                                                              
                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID , '期初结存',@BAMOUNT)
	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
                       SELECT  @BILLTYPENAME=NAME FROM  BILLNAME  WHERE @BILLTYPENAME=BILLTYPEID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
		IF @INOUTFLAG=1 
		BEGIN
			SELECT @INAMOUNT=@INAMOUNT
			SELECT @OUTAMOUNT=0
		END
		IF @INOUTFLAG=-1 
		BEGIN
			SELECT @OUTAMOUNT=@INAMOUNT
			SELECT @INAMOUNT=0
		END

                          INSERT    INTO   #temptable2  (ID,BILLID,BILLTYPE, BILLCODE,BILLDATE,BILLTYPENAME,
                                                               INAMOUNT,OUTAMOUNT,EAMOUNT)
                                           VALUES  (@COUNTID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INAMOUNT,@OUTAMOUNT,@EAMOUNT)
 		    SET @EAMOUNTPREV=@EAMOUNT

	    fetch INOUTMXBREP into   @ID,@BILLID,@BILLTYPE, @BILLCODE,@BILLDATE,@BILLTYPENAME,
                                                               @INAMOUNT,@OUTAMOUNT,@EAMOUNT,@INOUTFLAG
 

	    END           ------- INOUTMXBREP  WHILE
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期末结存',@EAMOUNT)

	    close INOUTMXBREP
	    deallocate INOUTMXBREP
        end     ------------  if exists
---------------------------
---------解决当前仓库本期间未发生业务的货品
--                  delete    #temptable1
            ELSE
            BEGIN
                           select @MAXBILLDATE=MAX(BILLDATE) FROM YunShuDWbillflow   WHERE  YunShuDWID=@YunShuDWID   AND     BILLDATE  < @begin_date    AND YYYYMMBILL=1
                           SELECT  @MAXID=MAX(ID)  FROM YunShuDWbillflow  WHERE  YunShuDWID=@YunShuDWID     AND  BILLDATE=@MAXBILLDATE   AND YYYYMMBILL=1

	             	  SELECT    @ID=ID,@EAMOUNT=EAMOUNT    FROM  YunShuDWbillflow  WHERE    ID =  @MAXID

                 SELECT @YunShuDWNAME=YunShuDWNAME   FROM YunShuDW  WHERE YunShuDWID=@YunShuDWID
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME         )
                                           VALUES  (@COUNTID,@YunShuDWNAME)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID

                                                              
                          INSERT    INTO   #temptable2  (ID , BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期初结存',@EAMOUNT)
	          set @COUNTID = rtrim(convert(char,convert(int,@COUNTID)+1))
	          set @COUNTID= substring('00000000',1,8-len(@COUNTID))+@COUNTID
                          INSERT    INTO   #temptable2  (ID, BILLTYPENAME,EAMOUNT)
                                           VALUES  (@COUNTID, '期末结存',@EAMOUNT)

---------------------------
	END




--------------------------

 SELECT *  FROM #temptable2         ORDER BY ID







----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG



















CREATE PROCEDURE YunShuDWYYYYMMDD(  @Begin_Date   varchar(10) ,
                                                                                           @End_date   varchar(10) ,  
                                                                                           @YYYYMM  varchar(8),      --------为当前会计期间
						           @YunShuDWCODE  varchar(20),             ---如果YunShuDWCODE  为‘GGGG’表示不对类别进行查询
						           @YunShuDWNAME  varchar(20)             ---如果YunShuDWNAME  为‘GGGG’表示不对类别进行查询
                         
                                                      ) as

Declare 
        @end_dateAddone  datetime,
        @now_date   varchar(10),
        @temp_year   varchar(10), 
        @temp_month   varchar(10),
        @temp_day   varchar(10),
        @SQLSTR   varchar(8000),
        @WHERESTING   varchar(1800)
                   set @now_date=(select   max(billDATE)   FROM  YunShuDWBILLFLOW)
                          IF @now_date IS NULL
		BEGIN
			set @now_date='2009-12-12'         ----以后纠正此特殊值，此值为调试程序用
		END

			SELECT    @WHERESTING  ='     '
		if     NOT (@YunShuDWCODE='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.YunShuDWID IN ( select  YunShuDWID from YunShuDW   where  CODE LIKE   '+CHAR(39)+'%'+@YunShuDWCODE+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  =@WHERESTING+'     '
 		END
		if     NOT (@YunShuDWNAME='GGGG')
                           BEGIN
	                           SELECT    @WHERESTING  = @WHERESTING+'  AND   I.YunShuDWID IN ( select  YunShuDWID from YunShuDW   where  YunShuDWNAME LIKE   '+CHAR(39)+'%'+@YunShuDWNAME+'%'+CHAR(39)+ '  )'
                           END
                           ELSE
                           BEGIN
			SELECT    @WHERESTING  = @WHERESTING+'     '
 		END

---                       print   @WHERESTING
----------------------------------------------------
		SELECT @SQLSTR='	 select  I.YunShuDWID,  I.CODE,  I.YunShuDWNAME  as NAME,       '
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0) -(isnull(BN.INAMOUNT,0)- isnull(BN00.INAMOUNT,0)) as BAMOUNT, '   --期初数量
		SELECT @SQLSTR=@SQLSTR+'ISNULL(BE.INAMOUNT,0)  AS INAMOUNT   ,ISNULL(BE00.INAMOUNT,0)  AS OUTAMOUNT,'
		SELECT @SQLSTR=@SQLSTR+'ISNULL(B.BAMOUNT,0)+ isnull(E.INAMOUNT,0) -(isnull(BN.INAMOUNT,0)- isnull(BN00.INAMOUNT,0))'
		SELECT @SQLSTR=@SQLSTR+'+ isnull(BE.INAMOUNT,0)-isnull(BE00.INAMOUNT,0) as EAMOUNT' --期末数量
		 SELECT @SQLSTR=@SQLSTR+' from YunShuDW  AS  I  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select YunShuDWID,sum(INAMOUNT*INOUTFLAG)  as INAMOUNT  '             --出入库总量
		 SELECT @SQLSTR=@SQLSTR+' from YunShuDWBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1    and  YYYYMM >= '+char(39)+@YYYYMM+char(39)
		SELECT @SQLSTR=@SQLSTR+'group by YunShuDWID'	
		SELECT @SQLSTR=@SQLSTR+') as E on E.YunShuDWID = I.YunShuDWID  '
		SELECT @SQLSTR=@SQLSTR+'left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select YunShuDWID,sum(BAMOUNT) as BAMOUNT '
		SELECT @SQLSTR=@SQLSTR+' from YunShuDWBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 0    and YYYYMM >='+char(39)+@YYYYMM+char(39) 
		SELECT @SQLSTR=@SQLSTR+' group by YunShuDWID'	
		SELECT @SQLSTR=@SQLSTR+' ) as B on B.YunShuDWID = I.YunShuDWID  '
------------------------以上部分是取当前库存
		SELECT @SQLSTR=@SQLSTR+'  left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select YunShuDWID,sum(INAMOUNT) as INAMOUNT      '
		SELECT @SQLSTR=@SQLSTR+'  from YunShuDWBILLFLOW           '
		SELECT @SQLSTR=@SQLSTR+'  where YYYYMMBILL = 1    and BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+ @Now_Date+char(39) +'  AND INOUTFLAG =1'   
		SELECT @SQLSTR=@SQLSTR+' group by YunShuDWID'	
		SELECT @SQLSTR=@SQLSTR+' ) as BN on BN.YunShuDWID = I.YunShuDWID'  
		SELECT @SQLSTR=@SQLSTR+'  left outer join '
		SELECT @SQLSTR=@SQLSTR+'  (  '
		SELECT @SQLSTR=@SQLSTR+'select YunShuDWID,sum(INAMOUNT) as INAMOUNT     '
		SELECT @SQLSTR=@SQLSTR+' from YunShuDWBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+ @Now_Date +char(39) +' AND INOUTFLAG =-1 '  
		SELECT @SQLSTR=@SQLSTR+' group by YunShuDWID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BN00 on BN00.YunShuDWID = I.YunShuDWID  '
------------------------以上部分为取begin_date到Now_Date的库存
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select YunShuDWID,sum(INAMOUNT) as INAMOUNT   '
		SELECT @SQLSTR=@SQLSTR+' from YunShuDWBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39) +'and  BILLDATE <='+char(39)+@End_Date+char(39)+' AND INOUTFLAG =1 '  
		SELECT @SQLSTR=@SQLSTR+' group by YunShuDWID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE on BE.YunShuDWID = I.YunShuDWID  '
		SELECT @SQLSTR=@SQLSTR+' left outer join '
		SELECT @SQLSTR=@SQLSTR+' ( '
		SELECT @SQLSTR=@SQLSTR+' select YunShuDWID,sum(INAMOUNT) as INAMOUNT   '
		SELECT @SQLSTR=@SQLSTR+' from YunShuDWBILLFLOW'
		SELECT @SQLSTR=@SQLSTR+' where YYYYMMBILL = 1   and BILLDATE >='+char(39)+@begin_date+char(39)+' and  BILLDATE <='+char(39)+@End_Date +char(39)+'AND INOUTFLAG =-1' 
		SELECT @SQLSTR=@SQLSTR+' group by YunShuDWID	'
		SELECT @SQLSTR=@SQLSTR+' ) as BE00 on BE00.YunShuDWID = I.YunShuDWID  '
                          SELECT @SQLSTR=@SQLSTR+'  where     I. YunShuDWID in (select YunShuDWID from YunShuDWBILLFLOW where YYYYMM >='+char(39)+@YYYYMM+char(39)+')'  + @WHERESTING 
	             SELECT @SQLSTR=@SQLSTR+'          order by  I.YunShuDWID                '    
------------------------------------------------------------------------
---	       print   @SQLSTR

		EXEC(@SQLSTR)








----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG














CREATE PROCEDURE [YunShuDW_CACULATOR_YYYYMM ]  (
	@YunShuDWID  varchar(30),
	@YYYYMM  varchar(6)    )
AS 
 
declare @INOUTFLAG NUMERIC(20,10)
declare @INAMOUNT  NUMERIC(20,10)
declare @EAMOUNT NUMERIC(20,10)
declare @SUMBAMOUNT NUMERIC(20,10)            ---本期期初总金额
 
BEGIN

            select    @SUMBAMOUNT=isnull(BAMOUNT,0)   FROM   YunShuDWBILLFlow  where    (rtrim(YunShuDWID) = @YunShuDWID) 
						  and (rtrim(YYYYMM) = @YYYYMM) 	and   ( YYYYMMBILL=0   )  
                                       -------以上是期初数据
----------------------------------------------------------------
	    declare YunShuDW_CACULATOR Cursor for Select  YunShuDWID , isnull(INAMOUNT,0) as INAMOUNT, INOUTFLAG, isnull(EAMOUNT,0) as EAMOUNT 
	                  from YunShuDWBILLFlow   where (rtrim(YYYYMM) >= @YYYYMM)  AND ( YunShuDWID=@YunShuDWID)   and   ( YYYYMMBILL=1   )  
             		      ORDER BY BILLDATE,ID

	    Open YunShuDW_CACULATOR

	    fetch YunShuDW_CACULATOR into @YunShuDWID,@INAMOUNT,@INOUTFLAG,@EAMOUNT


	    while @@fetch_status = 0            ----开始        以下过程是重新核算成本价和反填单据的单价
	    begin
		 select    @SUMBAMOUNT=@SUMBAMOUNT+@INAMOUNT*@INOUTFLAG

	         	 UPDATE   YunShuDWBILLFLOW  set   EAMOUNT=@SUMBAMOUNT      WHERE CURRENT OF  YunShuDW_CACULATOR

		    fetch YunShuDW_CACULATOR into @YunShuDWID,@INAMOUNT,@INOUTFLAG,@EAMOUNT
 
	    END           ------- YunShuDW_CACULATOR  WHILE

	    close YunShuDW_CACULATOR
	    deallocate YunShuDW_CACULATOR

-----------------------------------------------------------------------------------------------------------------------------------------------------------


END










----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG

SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS OFF 
----------ENDFLAG













CREATE            PROCEDURE initialCW_initbala
AS


---  SET XACT_ABORT ON

/*  DELETE FROM InitRate WHERE MoneyID=99

   Delete InitRate 
   From InitRate i, Currency c
   Where   NOT EXISTS    (Select MoneyID 
                                              From Currency
                                              WHERE  C.MoneyID = I.MoneyID   ) 

  INSERT INTO INITRATE
  SELECT c.MoneyID,c.Rate
  FROM Currency c
  WHERE c.MoneyID<99
    AND NOT EXISTS (Select MoneyID 
                                 From InitRate
                                  Where MoneyID = c.MoneyID )


  DELETE From	InitRate
  WHERE MoneyID=99
  INSERT INTO InitRate (MoneyID,Rate)
  VALUES(99,1)

  DELETE CW_initbala
  FROM CW_initbala a,Subject b
  WHERE --MnyIDSUBID =MnyIDSUBID AND 20070417 by lyh 多余
         a.SUBID=b.SUBID 
        AND b.HSWBFlag<2
        AND a.MoneyID<>b.MoneyID 
        AND b.DetailFlag='T'
        AND a.MoneyID<>99
        AND (a.Debit=0 OR a.Debit IS NULL)
        AND (a.Credit=0 OR a.Credit IS null)
        AND (a.BALANCE=0 OR a.BALANCE IS null)
         AND (a.PLHAVEDONE=0 OR a.PLHAVEDONE IS null)

  DELETE CW_initbala
  FROM CW_initbala i
  WHERE i.MoneyID<>99 
       AND NOT EXISTS(select MoneyID  from InitRate where  i.MoneyID= MoneyID )
       OR NOT EXISTS (select SubID from subject  where  i.SubID = SubID )


  INSERT INTO CW_initbala(MONEYID,Rate,SUBID)
  SELECT A.MoneyID,A.RATE,B.SUBID
  FROM InitRate A, Subject b
  WHERE NOT EXISTS(SELECT * 
                   FROM CW_initbala c 
                   WHERE a.MoneyID=c.MoneyID 
                   AND b.SUBID=c.SUBID)
    AND (a.MoneyID=99
    OR b.HSWBFlag=2
    --OR b.DetailFlag='F'
    OR  (b.HSWBFlag<2 AND a.MONEYID=b.MoneyID))
    and b.DetailFlag='T'


  DELETE 
  FROM InitRate 
  WHERE MoneyID=99
*/

  insert into CW_INITBALA (itembm)
	select itembm from ItemInfo where detailflag=1 and (itembm NOT IN (select itembm from CW_INITBALA))	

  Delete CW_INITBALA where itembm not in ( select itembm from ItemInfo where detailflag=1 )

  UPDATE CW_initbala SET Debit=0 WHERE Debit IS Null
  UPDATE CW_initbala SET Credit=0 WHERE Credit IS Null
  UPDATE CW_initbala SET Balance=0 WHERE Balance IS Null
  UPDATE CW_initbala SET PLHAVEDONE=0 WHERE PLHAVEDONE IS Null
  UPDATE CW_initbala SET DCFlag=b.JHD From CW_initbala a, ItemInfo b  WHERE a.itembm=b.itembm











----------ENDFLAG
SET QUOTED_IDENTIFIER OFF 
----------ENDFLAG
SET ANSI_NULLS ON 
----------ENDFLAG


delete SETCOL 
----------ENDFLAG


  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'VENDORName', '20','供应商','F','APGCTXP','FormCGMXB',0,'1','01','20','供应商','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'EMPNAME', '10','业务员','F','APGCTXP','FormCGMXB',0,'1','02','10','业务员','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STORENAME', '10','仓库名称','F','APGCTXP','FormCGMXB',0,'1','03','10','仓库名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CODE', '20','单据号','F','APGCTXP','FormCGMXB',0,'1','04','20','单据号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'BILLDATE', '10','单据日期','F','APGCTXP','FormCGMXB',0,'1','05','10','单据日期','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'OLDBILLCODE', '10','原始单号','F','APGCTXP','FormCGMXB',0,'1','06','10','原始单号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GoodsCode', '10','钢材编号','F','APGCTXP','FormCGMXB',0,'1','07','10','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','FormCGMXB',0,'1','08','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '12','规格','F','APGCTXP','FormCGMXB',0,'1','09','12','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDu', '10','长度','F','APGCTXP','FormCGMXB',0,'1','10','10','长度','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChanDi', '10','产地','F','APGCTXP','FormCGMXB',0,'1','11','10','产地','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CaiZhi', '10','材质','F','APGCTXP','FormCGMXB',0,'1','12','10','材质','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '10','产地D','F','APGCTXP','FormCGMXB',0,'1','13','10','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','FormCGMXB',0,'1','14','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '10','数量','F','APGCTXP','FormCGMXB',0,'1','15','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '4','单位','F','APGCTXP','FormCGMXB',0,'1','16','4','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'FuZhuQTY', '16','辅助数量','F','APGCTXP','FormCGMXB',0,'1','17','16','辅助数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '12','重量(吨)','F','APGCTXP','FormCGMXB',0,'1','18','12','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'PRICETYPENAME', '6','计价类别','F','APGCTXP','FormCGMXB',0,'1','19','6','计价类别','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITPRICE', '10','单价','F','APGCTXP','FormCGMXB',0,'1','20','10','单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'DISC', '10','折扣比率','F','APGCTXP','FormCGMXB',0,'1','21','10','折扣比率','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '12','金额','F','APGCTXP','FormCGMXB',0,'1','22','12','金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXRATE', '10','税率','F','APGCTXP','FormCGMXB',0,'1','23','10','税率','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXJIN', '10','税金','F','APGCTXP','FormCGMXB',0,'1','24','10','税金','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXAMT', '10','价税合计','F','APGCTXP','FormCGMXB',0,'1','25','10','价税合计','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '20','自定义列1','F','APGCTXP','FormCGMXB',0,'1','26','20','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '20','自定义列2','F','APGCTXP','FormCGMXB',0,'1','27','20','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GoodsCode', '10','钢材编号','F','APGCTXP','FormCKHZTJB',0,'1','01','10','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','FormCKHZTJB',0,'1','02','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '12','规格','F','APGCTXP','FormCKHZTJB',0,'1','03','12','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDu', '10','长度','F','APGCTXP','FormCKHZTJB',0,'1','04','10','长度','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '10','产地D','F','APGCTXP','FormCKHZTJB',0,'1','05','10','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','FormCKHZTJB',0,'1','06','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '10','数量','F','APGCTXP','FormCKHZTJB',0,'1','07','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '4','单位','F','APGCTXP','FormCKHZTJB',0,'1','08','4','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'FuZhuQTY', '16','辅助数量','F','APGCTXP','FormCKHZTJB',0,'1','09','16','辅助数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '12','重量(吨)','F','APGCTXP','FormCKHZTJB',0,'1','10','12','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '12','金额','F','APGCTXP','FormCKHZTJB',0,'1','11','12','金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '20','自定义列1','F','APGCTXP','FormCKHZTJB',0,'1','12','20','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '20','自定义列2','F','APGCTXP','FormCKHZTJB',0,'1','13','20','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'EMPNAME', '6','业务员','F','APGCTXP','FormCKMXB',0,'1','01','6','业务员','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STORENAME', '8','仓库名称','F','APGCTXP','FormCKMXB',0,'1','02','8','仓库名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CODE', '20','单据号','F','APGCTXP','FormCKMXB',0,'1','03','20','单据号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'BILLDATE', '10','单据日期','F','APGCTXP','FormCKMXB',0,'1','04','10','单据日期','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'OLDBILLCODE', '10','原始单号','F','APGCTXP','FormCKMXB',0,'1','05','10','原始单号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GoodsCode', '10','钢材编号','F','APGCTXP','FormCKMXB',0,'1','06','10','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','FormCKMXB',0,'1','07','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '12','规格','F','APGCTXP','FormCKMXB',0,'1','08','12','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDu', '10','长度','F','APGCTXP','FormCKMXB',0,'1','09','10','长度','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChanDi', '10','产地','F','APGCTXP','FormCKMXB',0,'1','10','10','产地','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CaiZhi', '10','材质','F','APGCTXP','FormCKMXB',0,'1','11','10','材质','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '10','产地D','F','APGCTXP','FormCKMXB',0,'1','12','10','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','FormCKMXB',0,'1','13','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '10','数量','F','APGCTXP','FormCKMXB',0,'1','14','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '4','单位','F','APGCTXP','FormCKMXB',0,'1','15','4','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'FuZhuQTY', '16','辅助数量','T','APGCTXP','FormCKMXB',0,'1','16','16','辅助数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '12','重量(吨)','F','APGCTXP','FormCKMXB',0,'1','17','12','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'PRICETYPENAME', '6','计价类别','F','APGCTXP','FormCKMXB',0,'1','18','6','计价类别','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITPRICE', '10','单价','F','APGCTXP','FormCKMXB',0,'1','19','10','单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '12','金额','F','APGCTXP','FormCKMXB',0,'1','20','12','金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '20','自定义列1','F','APGCTXP','FormCKMXB',0,'1','21','20','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '20','自定义列2','F','APGCTXP','FormCKMXB',0,'1','22','20','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'BILLCODE', '20','单号','F','APGCTXP','FormCLIENTXSCKMXB',0,'1','01','20','单号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'BILLDATE', '10','单据日期','F','APGCTXP','FormCLIENTXSCKMXB',0,'1','02','10','单据日期','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSCODE', '16','钢材编号','F','APGCTXP','FormCLIENTXSCKMXB',0,'1','03','16','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','FormCLIENTXSCKMXB',0,'1','04','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '10','规格','F','APGCTXP','FormCLIENTXSCKMXB',0,'1','05','10','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDu', '10','长度','F','APGCTXP','FormCLIENTXSCKMXB',0,'1','06','10','长度','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChanDi', '10','产地','F','APGCTXP','FormCLIENTXSCKMXB',0,'1','07','10','产地','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CaiZhi', '10','材质','F','APGCTXP','FormCLIENTXSCKMXB',0,'1','08','10','材质','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '10','产地D','F','APGCTXP','FormCLIENTXSCKMXB',0,'1','09','10','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','FormCLIENTXSCKMXB',0,'1','10','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '4','单位','F','APGCTXP','FormCLIENTXSCKMXB',0,'1','11','4','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'FuZhuQTY', '16','辅助数量','T','APGCTXP','FormCLIENTXSCKMXB',0,'1','12','16','辅助数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '10','数量/重量(吨)','F','APGCTXP','FormCLIENTXSCKMXB',0,'1','13','10','数量/重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'PRICETYPENAME', '8','计价类别','F','APGCTXP','FormCLIENTXSCKMXB',0,'1','14','8','计价类别','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'PRICE', '10','单价','F','APGCTXP','FormCLIENTXSCKMXB',0,'1','15','10','单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXRATE', '4','税率','F','APGCTXP','FormCLIENTXSCKMXB',0,'1','16','4','税率','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '12','货款金额','F','APGCTXP','FormCLIENTXSCKMXB',0,'1','17','12','货款金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXAMT', '12','价税合计','F','APGCTXP','FormCLIENTXSCKMXB',0,'1','18','12','价税合计','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '20','自定义列1','F','APGCTXP','FormCLIENTXSCKMXB',0,'1','19','20','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '20','自定义列2','F','APGCTXP','FormCLIENTXSCKMXB',0,'1','20','20','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SpecNameD', '20','规格D','F','APGCTXP','FormCLIENTXSCKMXB',0,'1','21','20','规格D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GoodsCode', '10','钢材编号','F','APGCTXP','FormDBHZTJB',0,'1','01','10','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','FormDBHZTJB',0,'1','02','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '12','规格','F','APGCTXP','FormDBHZTJB',0,'1','03','12','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDu', '10','长度','F','APGCTXP','FormDBHZTJB',0,'1','04','10','长度','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '10','产地D','F','APGCTXP','FormDBHZTJB',0,'1','05','10','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','FormDBHZTJB',0,'1','06','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '10','数量','F','APGCTXP','FormDBHZTJB',0,'1','07','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '4','单位','F','APGCTXP','FormDBHZTJB',0,'1','08','4','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'FuZhuQTY', '16','辅助数量','F','APGCTXP','FormDBHZTJB',0,'1','09','16','辅助数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '12','重量(吨)','F','APGCTXP','FormDBHZTJB',0,'1','10','12','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '12','金额','F','APGCTXP','FormDBHZTJB',0,'1','11','12','金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '20','自定义列1','F','APGCTXP','FormDBHZTJB',0,'1','12','20','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '20','自定义列2','F','APGCTXP','FormDBHZTJB',0,'1','13','20','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CODE', '20','单据号','F','APGCTXP','FormDBMXB',0,'1','01','20','单据号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'BILLDATE', '10','单据日期','F','APGCTXP','FormDBMXB',0,'1','02','10','单据日期','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GoodsCode', '10','钢材编号','F','APGCTXP','FormDBMXB',0,'1','03','10','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','FormDBMXB',0,'1','04','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '12','规格','F','APGCTXP','FormDBMXB',0,'1','05','12','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDu', '10','长度','F','APGCTXP','FormDBMXB',0,'1','06','10','长度','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChanDi', '10','产地','F','APGCTXP','FormDBMXB',0,'1','07','10','产地','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CaiZhi', '10','材质','F','APGCTXP','FormDBMXB',0,'1','08','10','材质','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '10','产地D','F','APGCTXP','FormDBMXB',0,'1','09','10','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','FormDBMXB',0,'1','10','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '10','数量','F','APGCTXP','FormDBMXB',0,'1','11','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '4','单位','F','APGCTXP','FormDBMXB',0,'1','12','4','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'FuZhuQTY', '16','辅助数量','F','APGCTXP','FormDBMXB',0,'1','13','16','辅助数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '10','重量(吨)','F','APGCTXP','FormDBMXB',0,'1','14','10','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'PRICETYPENAME', '8','计价类别','F','APGCTXP','FormDBMXB',0,'1','15','8','计价类别','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITPRICE', '10','单价','F','APGCTXP','FormDBMXB',0,'1','16','10','单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '12','金额','F','APGCTXP','FormDBMXB',0,'1','17','12','金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '20','自定义列1','F','APGCTXP','FormDBMXB',0,'1','18','20','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '20','自定义列2','F','APGCTXP','FormDBMXB',0,'1','19','20','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GoodsCode', '10','钢材编号','F','APGCTXP','FormPDHZTJB',0,'1','01','10','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','FormPDHZTJB',0,'1','02','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '12','规格','F','APGCTXP','FormPDHZTJB',0,'1','03','12','规格','1')
----------ENDFLAG
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDu', '10','长度','F','APGCTXP','FormPDHZTJB',0,'1','04','10','长度','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '10','产地D','F','APGCTXP','FormPDHZTJB',0,'1','05','10','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','FormPDHZTJB',0,'1','06','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '10','实际数量','F','APGCTXP','FormPDHZTJB',0,'1','07','10','实际数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITPRICE', '10','帐面数量','F','APGCTXP','FormPDHZTJB',0,'1','08','10','帐面数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MYKQTY', '10','盈亏数量','F','APGCTXP','FormPDHZTJB',0,'1','09','10','盈亏数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '4','单位','F','APGCTXP','FormPDHZTJB',0,'1','10','4','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '10','实际重量(吨)','F','APGCTXP','FormPDHZTJB',0,'1','11','10','实际重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'PRICE', '10','帐面重量(吨)','F','APGCTXP','FormPDHZTJB',0,'1','12','10','帐面重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'YKQTY', '10','盈亏重量(吨)','F','APGCTXP','FormPDHZTJB',0,'1','13','10','盈亏重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '20','自定义列1','F','APGCTXP','FormPDHZTJB',0,'1','14','20','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '20','自定义列2','F','APGCTXP','FormPDHZTJB',0,'1','15','20','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CODE', '20','单据号','F','APGCTXP','FormPDMXB',0,'1','01','20','单据号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'BILLDATE', '10','单据日期','F','APGCTXP','FormPDMXB',0,'1','02','10','单据日期','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GoodsCode', '10','钢材编号','F','APGCTXP','FormPDMXB',0,'1','03','10','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','FormPDMXB',0,'1','04','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '12','规格','F','APGCTXP','FormPDMXB',0,'1','05','12','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDu', '10','长度','F','APGCTXP','FormPDMXB',0,'1','06','10','长度','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChanDi', '10','产地','F','APGCTXP','FormPDMXB',0,'1','07','10','产地','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CaiZhi', '10','材质','F','APGCTXP','FormPDMXB',0,'1','08','10','材质','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '10','产地D','F','APGCTXP','FormPDMXB',0,'1','09','10','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','FormPDMXB',0,'1','10','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '10','实际数量','F','APGCTXP','FormPDMXB',0,'1','11','10','实际数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITPRICE', '10','帐面数量','F','APGCTXP','FormPDMXB',0,'1','12','10','帐面数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MYKQTY', '10','盈亏数量','F','APGCTXP','FormPDMXB',0,'1','13','10','盈亏数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '4','单位','F','APGCTXP','FormPDMXB',0,'1','14','4','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '10','实际重量(吨)','F','APGCTXP','FormPDMXB',0,'1','15','10','实际重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'PRICE', '10','帐面重量(吨)','F','APGCTXP','FormPDMXB',0,'1','16','10','帐面重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'YKQTY', '10','盈亏重量(吨)','F','APGCTXP','FormPDMXB',0,'1','17','10','盈亏重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '20','自定义列1','F','APGCTXP','FormPDMXB',0,'0','18','20','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '20','自定义列2','F','APGCTXP','FormPDMXB',0,'0','19','20','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GoodsCode', '10','钢材编号','F','APGCTXP','FormRKHZTJB',0,'1','01','10','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','FormRKHZTJB',0,'1','02','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '12','规格','F','APGCTXP','FormRKHZTJB',0,'1','03','12','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDu', '10','长度','F','APGCTXP','FormRKHZTJB',0,'1','04','10','长度','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '10','产地D','F','APGCTXP','FormRKHZTJB',0,'1','05','10','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','FormRKHZTJB',0,'1','06','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '10','数量','F','APGCTXP','FormRKHZTJB',0,'1','07','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '4','单位','F','APGCTXP','FormRKHZTJB',0,'1','08','4','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'FuZhuQTY', '16','辅助数量','F','APGCTXP','FormRKHZTJB',0,'1','09','16','辅助数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '12','重量(吨)','F','APGCTXP','FormRKHZTJB',0,'1','10','12','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '12','金额','F','APGCTXP','FormRKHZTJB',0,'1','11','12','金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '20','自定义列1','F','APGCTXP','FormRKHZTJB',0,'1','12','20','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '20','自定义列2','F','APGCTXP','FormRKHZTJB',0,'1','13','20','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'EMPNAME', '6','业务员','F','APGCTXP','FormRKMXB',0,'1','01','6','业务员','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STORENAME', '8','仓库名称','F','APGCTXP','FormRKMXB',0,'1','02','8','仓库名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CODE', '20','单据号','F','APGCTXP','FormRKMXB',0,'1','03','20','单据号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'BILLDATE', '10','单据日期','F','APGCTXP','FormRKMXB',0,'1','04','10','单据日期','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'OLDBILLCODE', '10','原始单号','F','APGCTXP','FormRKMXB',0,'1','05','10','原始单号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GoodsCode', '10','钢材编号','F','APGCTXP','FormRKMXB',0,'1','06','10','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','FormRKMXB',0,'1','07','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '12','规格','F','APGCTXP','FormRKMXB',0,'1','08','12','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDu', '10','长度','F','APGCTXP','FormRKMXB',0,'1','09','10','长度','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChanDi', '10','产地','F','APGCTXP','FormRKMXB',0,'1','10','10','产地','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CaiZhi', '10','材质','F','APGCTXP','FormRKMXB',0,'1','11','10','材质','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '10','产地D','F','APGCTXP','FormRKMXB',0,'1','12','10','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','FormRKMXB',0,'1','13','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '10','数量','F','APGCTXP','FormRKMXB',0,'1','14','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '4','单位','F','APGCTXP','FormRKMXB',0,'1','15','4','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'FuZhuQTY', '16','辅助数量','F','APGCTXP','FormRKMXB',0,'1','16','16','辅助数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '12','重量(吨)','F','APGCTXP','FormRKMXB',0,'1','17','12','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'PRICETYPENAME', '6','计价类别','F','APGCTXP','FormRKMXB',0,'1','18','6','计价类别','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITPRICE', '10','单价','F','APGCTXP','FormRKMXB',0,'1','19','10','单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '12','金额','F','APGCTXP','FormRKMXB',0,'1','20','12','金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '20','自定义列1','F','APGCTXP','FormRKMXB',0,'1','21','20','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '20','自定义列2','F','APGCTXP','FormRKMXB',0,'1','22','20','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GoodsCode', '16','钢材编码','F','APGCTXP','FormStoreDoubleHZTJB',0,'1','01','16','钢材编码','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','FormStoreDoubleHZTJB',0,'1','02','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '12','钢材规格','F','APGCTXP','FormStoreDoubleHZTJB',0,'1','03','12','钢材规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDu', '10','长度','F','APGCTXP','FormStoreDoubleHZTJB',0,'1','04','10','长度','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '10','产地D','F','APGCTXP','FormStoreDoubleHZTJB',0,'1','05','10','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','FormStoreDoubleHZTJB',0,'1','06','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'unitqty', '10','数量','F','APGCTXP','FormStoreDoubleHZTJB',0,'1','07','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '4','单位','F','APGCTXP','FormStoreDoubleHZTJB',0,'1','08','4','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'FuZhuQTY', '16','辅助数量','F','APGCTXP','FormStoreDoubleHZTJB',0,'1','09','16','辅助数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '12','重量(吨)','F','APGCTXP','FormStoreDoubleHZTJB',0,'1','10','12','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '16','货款金额','F','APGCTXP','FormStoreDoubleHZTJB',0,'1','11','16','货款金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXAMT', '16','价税合计','F','APGCTXP','FormStoreDoubleHZTJB',0,'1','12','16','价税合计','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '20','自定义列1','F','APGCTXP','FormStoreDoubleHZTJB',0,'1','13','20','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '20','自定义列2','F','APGCTXP','FormStoreDoubleHZTJB',0,'1','14','20','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GoodsCode', '16','钢材编号','F','APGCTXP','FormSTOREHZB',1,'1','01','16','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','FormSTOREHZB',1,'1','02','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '10','钢材规格','F','APGCTXP','FormSTOREHZB',1,'1','03','10','钢材规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质','F','APGCTXP','FormSTOREHZB',1,'1','04','10','材质','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '10','产地','F','APGCTXP','FormSTOREHZB',1,'1','05','10','产地','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '4','单位','F','APGCTXP','FormSTOREHZB',1,'1','06','4','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MBQTY', '10','数量','F','上期结存','APGCTXP','FormSTOREHZB','1','1','07','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'BQTY', '10','重量(吨)','F','上期结存','APGCTXP','FormSTOREHZB','1','1','08','10','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'BAMOUNT', '10','金额','F','上期结存','APGCTXP','FormSTOREHZB','1','1','09','10','金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MINQTY', '10','数量','F','本期收入','APGCTXP','FormSTOREHZB','1','1','10','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'INQTY', '10','重量(吨)','F','本期收入','APGCTXP','FormSTOREHZB','1','1','11','10','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'INAMOUNT', '10','金额','F','本期收入','APGCTXP','FormSTOREHZB','1','1','12','10','金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MOUTQTY', '10','数量','F','本期发出','APGCTXP','FormSTOREHZB','1','1','13','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'OUTQTY', '10','重量(吨)','F','本期发出','APGCTXP','FormSTOREHZB','1','1','14','10','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'OUTAMOUNT', '10','金额','F','本期发出','APGCTXP','FormSTOREHZB','1','1','15','10','金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MEQTY', '10','数量','F','本期结存','APGCTXP','FormSTOREHZB','1','1','16','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'EQTY', '10','重量(吨)','F','本期结存','APGCTXP','FormSTOREHZB','1','1','17','10','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'EAMOUNT', '10','金额','F','本期结存','APGCTXP','FormSTOREHZB','1','1','18','10','金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '20','自定义列1','F','APGCTXP','FormSTOREHZB',1,'1','19','20','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '20','自定义列2','F','APGCTXP','FormSTOREHZB',1,'1','20','20','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'DSPRICETax', '16','销售价含税(吨)','F','APGCTXP','FormSTOREHZB',1,'1','21','16','销售价含税(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MQTYSPRICE', '21','销售价(每数量单位)','F','APGCTXP','FormSTOREHZB',1,'1','22','21','销售价(每数量单位)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GoodsCode', '16','钢材编号','F','APGCTXP','FormSTORELEDGER',0,'1','01','16','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','FormSTORELEDGER',0,'1','02','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '16','规格','F','APGCTXP','FormSTORELEDGER',0,'1','03','16','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDuMi', '10','长度(米)','F','APGCTXP','FormSTORELEDGER',0,'1','04','10','长度(米)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质','F','APGCTXP','FormSTORELEDGER',0,'1','05','10','材质','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '10','产地','F','APGCTXP','FormSTORELEDGER',0,'1','06','10','产地','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ZaiTuUNITQTY', '10','在途数量','F','APGCTXP','FormSTORELEDGER',0,'1','07','10','在途数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'KeYongUnitQty', '15','可用库存数量','F','APGCTXP','FormSTORELEDGER',0,'1','08','15','可用库存数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '10','库存数量','F','APGCTXP','FormSTORELEDGER',0,'1','09','10','库存数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '4','单位','F','APGCTXP','FormSTORELEDGER',0,'1','10','4','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'FuZhuQTY', '16','辅助数量','T','APGCTXP','FormSTORELEDGER',0,'1','11','16','辅助数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ZaiTuQuanTity', '10','在途重量(吨)','F','APGCTXP','FormSTORELEDGER',0,'1','12','10','在途重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'KeYongQuanTity', '10','可用库存重量(吨)','F','APGCTXP','FormSTORELEDGER',0,'1','13','10','可用库存重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'EQTY', '10','库存重量(吨)','F','APGCTXP','FormSTORELEDGER',0,'1','14','10','库存重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'EPRICE', '10','成本价','F','APGCTXP','FormSTORELEDGER',0,'1','15','10','成本价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'EAMOUNT', '10','库存金额','F','APGCTXP','FormSTORELEDGER',0,'1','16','10','库存金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'DSPRICE', '10','销售报价(吨)','F','APGCTXP','FormSTORELEDGER',0,'1','17','10','销售报价(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LLZhongLiang', '10','理论重量','F','APGCTXP','FormSTORELEDGER',0,'1','18','10','理论重量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'DSPRICETax', '10','销售报价(吨)含税','F','APGCTXP','FormSTORELEDGER',0,'1','19','10','销售报价(吨)含税','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LSRATE', '10','理论系数','F','APGCTXP','FormSTORELEDGER',0,'1','20','10','理论系数','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MQTYSPRICE', '10','销售报价(每数量单位)','F','APGCTXP','FormSTORELEDGER',0,'1','21','10','销售报价(每数量单位)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '20','自定义列1','F','APGCTXP','FormSTORELEDGER',0,'1','22','20','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '20','自定义列2','F','APGCTXP','FormSTORELEDGER',0,'1','23','20','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MiZhong', '10','米重(公斤)','F','APGCTXP','FormSTORELEDGER',0,'1','24','10','米重(公斤)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ZongLen', '10','总长度(米)','F','APGCTXP','FormSTORELEDGER',0,'1','25','10','总长度(米)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MEPRICE', '10','数量成本价','F','APGCTXP','FormSTORELEDGER',0,'1','26','10','数量成本价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GoodsCode', '16','钢材编号','F','APGCTXP','FormSTORELEDGER_QTY',0,'1','01','16','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','FormSTORELEDGER_QTY',0,'1','02','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '16','规格','F','APGCTXP','FormSTORELEDGER_QTY',0,'1','03','16','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDu', '10','长度','F','APGCTXP','FormSTORELEDGER_QTY',0,'1','04','10','长度','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质','F','APGCTXP','FormSTORELEDGER_QTY',0,'1','05','10','材质','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '10','产地','F','APGCTXP','FormSTORELEDGER_QTY',0,'1','06','10','产地','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ZaiTuUNITQTY', '10','在途数量','F','APGCTXP','FormSTORELEDGER_QTY',0,'1','07','10','在途数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'KeYongUnitQty', '15','可用库存数量','F','APGCTXP','FormSTORELEDGER_QTY',0,'1','08','15','可用库存数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '10','库存数量','F','APGCTXP','FormSTORELEDGER_QTY',0,'1','09','10','库存数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '4','单位','F','APGCTXP','FormSTORELEDGER_QTY',0,'1','10','4','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'FuZhuQTY', '16','辅助数量','T','APGCTXP','FormSTORELEDGER_QTY',0,'1','11','16','辅助数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ZaiTuQuanTity', '10','在途重量(吨)','F','APGCTXP','FormSTORELEDGER_QTY',0,'1','12','10','在途重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'KeYongQuanTity', '10','可用库存重量(吨)','F','APGCTXP','FormSTORELEDGER_QTY',0,'1','13','10','可用库存重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'EQTY', '10','库存重量(吨)','F','APGCTXP','FormSTORELEDGER_QTY',0,'1','14','10','库存重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'DSPRICE', '10','销售报价(吨)','F','APGCTXP','FormSTORELEDGER_QTY',0,'1','15','10','销售报价(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LLZhongLiang', '10','理论重量','F','APGCTXP','FormSTORELEDGER_QTY',0,'1','16','10','理论重量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'DSPRICETax', '10','销售报价(吨)含税','F','APGCTXP','FormSTORELEDGER_QTY',0,'1','17','10','销售报价(吨)含税','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LSRATE', '10','理论系数','F','APGCTXP','FormSTORELEDGER_QTY',0,'1','18','10','理论系数','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MQTYSPRICE', '10','销售报价(每数量单位)','F','APGCTXP','FormSTORELEDGER_QTY',0,'1','19','10','销售报价(每数量单位)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '20','自定义列1','F','APGCTXP','FormSTORELEDGER_QTY',0,'1','20','20','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '20','自定义列2','F','APGCTXP','FormSTORELEDGER_QTY',0,'1','21','20','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GoodsCode', '16','钢材编号','F','APGCTXP','FormSTORELEDGER_XIAN',0,'1','01','16','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','FormSTORELEDGER_XIAN',0,'1','02','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '16','规格','F','APGCTXP','FormSTORELEDGER_XIAN',0,'1','03','16','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质','F','APGCTXP','FormSTORELEDGER_XIAN',0,'1','04','10','材质','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '10','产地','F','APGCTXP','FormSTORELEDGER_XIAN',0,'1','05','10','产地','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MEQTY', '10','数量','F','APGCTXP','FormSTORELEDGER_XIAN',0,'1','06','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '4','单位','F','APGCTXP','FormSTORELEDGER_XIAN',0,'1','07','4','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'EQTY', '12','重量(吨)','F','APGCTXP','FormSTORELEDGER_XIAN',0,'1','08','12','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'EPRICE', '10','成本价','F','APGCTXP','FormSTORELEDGER_XIAN',0,'1','09','10','成本价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'EAMOUNT', '10','库存金额','F','APGCTXP','FormSTORELEDGER_XIAN',0,'1','10','10','库存金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '20','自定义列1','F','APGCTXP','FormSTORELEDGER_XIAN',0,'1','11','20','自定义列1','1')
----------ENDFLAG
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '20','自定义列2','F','APGCTXP','FormSTORELEDGER_XIAN',0,'1','12','20','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'BILLCODE', '20','单据号','F','APGCTXP','FormSTOREMXB',1,'1','01','20','单据号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','FormSTOREMXB',1,'1','02','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '20','规格','F','APGCTXP','FormSTOREMXB',1,'1','03','20','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'BILLDATE', '10','开单日期','F','APGCTXP','FormSTOREMXB',1,'1','04','10','开单日期','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'BILLTYPENAME', '10','业务类型','F','APGCTXP','FormSTOREMXB',1,'1','05','10','业务类型','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '4','单位','F','APGCTXP','FormSTOREMXB',1,'1','06','4','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MINQTY', '10','数量','F','本期收入','APGCTXP','FormSTOREMXB','1','1','07','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MINPRICE', '10','数量单价','F','本期收入','APGCTXP','FormSTOREMXB','1','1','08','10','数量单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'INQTY', '10','重量(吨)','F','本期收入','APGCTXP','FormSTOREMXB','1','1','09','10','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'INPRICE', '10','单价','F','本期收入','APGCTXP','FormSTOREMXB','1','1','10','10','单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'INAMOUNT', '10','金额','F','本期收入','APGCTXP','FormSTOREMXB','1','1','11','10','金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MOUTQTY', '10','数量','F','本期发出','APGCTXP','FormSTOREMXB','1','1','12','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MOUTPRICE', '10','数量单价','F','本期发出','APGCTXP','FormSTOREMXB','1','1','13','10','数量单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'OUTQTY', '10','重量(吨)','F','本期发出','APGCTXP','FormSTOREMXB','1','1','14','10','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'OUTPRICE', '10','单价','F','本期发出','APGCTXP','FormSTOREMXB','1','1','15','10','单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'OUTAMOUNT', '10','金额','F','本期发出','APGCTXP','FormSTOREMXB','1','1','16','10','金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MEQTY', '10','数量','F','结存','APGCTXP','FormSTOREMXB','1','1','17','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MEPRICE', '10','数量单价','F','结存','APGCTXP','FormSTOREMXB','1','1','18','10','数量单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'EQTY', '10','重量(吨)','F','结存','APGCTXP','FormSTOREMXB','1','1','19','10','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'EPRICE', '10','单价','F','结存','APGCTXP','FormSTOREMXB','1','1','20','10','单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,FGROUP,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'EAMOUNT', '10','金额','F','结存','APGCTXP','FormSTOREMXB','1','1','21','10','金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GoodsCode', '10','钢材编码','F','APGCTXP','FormSTOREMXB',1,'1','22','10','钢材编码','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '10','产地D','F','APGCTXP','FormSTOREMXB',1,'1','23','10','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','FormSTOREMXB',1,'1','24','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAMED', '20','规格D','F','APGCTXP','FormSTOREMXB',1,'1','25','20','规格D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'BILLCODE', '20','单号','F','APGCTXP','FormVENDORCGRKMXB',0,'1','01','20','单号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'BILLDATE', '10','单据日期','F','APGCTXP','FormVENDORCGRKMXB',0,'1','02','10','单据日期','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSCODE', '16','钢材编号','F','APGCTXP','FormVENDORCGRKMXB',0,'1','03','16','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','FormVENDORCGRKMXB',0,'1','04','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '10','钢材规格','F','APGCTXP','FormVENDORCGRKMXB',0,'1','05','10','钢材规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDu', '10','长度','F','APGCTXP','FormVENDORCGRKMXB',0,'1','06','10','长度','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChanDi', '10','产地','F','APGCTXP','FormVENDORCGRKMXB',0,'1','07','10','产地','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CaiZhi', '10','材质','F','APGCTXP','FormVENDORCGRKMXB',0,'1','08','10','材质','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '10','产地D','F','APGCTXP','FormVENDORCGRKMXB',0,'1','09','10','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','FormVENDORCGRKMXB',0,'1','10','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '4','单位','F','APGCTXP','FormVENDORCGRKMXB',0,'1','11','4','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'FuZhuQTY', '16','辅助数量','F','APGCTXP','FormVENDORCGRKMXB',0,'1','12','16','辅助数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '10','数量/重量(吨)','F','APGCTXP','FormVENDORCGRKMXB',0,'1','13','10','数量/重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'PRICETYPENAME', '8','计价类别','F','APGCTXP','FormVENDORCGRKMXB',0,'1','14','8','计价类别','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'PRICE', '10','单价','F','APGCTXP','FormVENDORCGRKMXB',0,'1','15','10','单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXRATE', '4','税率','F','APGCTXP','FormVENDORCGRKMXB',0,'1','16','4','税率','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '12','货款金额','F','APGCTXP','FormVENDORCGRKMXB',0,'1','17','12','货款金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXAMT', '12','价税合计','F','APGCTXP','FormVENDORCGRKMXB',0,'1','18','12','价税合计','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '20','自定义列1','F','APGCTXP','FormVENDORCGRKMXB',0,'1','19','20','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '20','自定义列2','F','APGCTXP','FormVENDORCGRKMXB',0,'1','20','20','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GoodsCode', '16','钢材编码','F','APGCTXP','FormXSCKBILLHZTJB',0,'1','01','16','钢材编码','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','FormXSCKBILLHZTJB',0,'1','02','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '12','钢材规格','F','APGCTXP','FormXSCKBILLHZTJB',0,'1','03','12','钢材规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDu', '10','长度','F','APGCTXP','FormXSCKBILLHZTJB',0,'1','04','10','长度','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '10','产地D','F','APGCTXP','FormXSCKBILLHZTJB',0,'1','05','10','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','FormXSCKBILLHZTJB',0,'1','06','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '10','数量','F','APGCTXP','FormXSCKBILLHZTJB',0,'1','07','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '4','单位','F','APGCTXP','FormXSCKBILLHZTJB',0,'1','08','4','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'FuZhuQTY', '16','辅助数量','F','APGCTXP','FormXSCKBILLHZTJB',0,'1','09','16','辅助数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '12','重量(吨)','F','APGCTXP','FormXSCKBILLHZTJB',0,'1','10','12','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '12','货款金额','F','APGCTXP','FormXSCKBILLHZTJB',0,'1','11','12','货款金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXAMT', '12','价税合计','F','APGCTXP','FormXSCKBILLHZTJB',0,'1','12','12','价税合计','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '20','自定义列1','F','APGCTXP','FormXSCKBILLHZTJB',0,'1','13','20','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '20','自定义列2','F','APGCTXP','FormXSCKBILLHZTJB',0,'1','14','20','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GoodsCode', '16','钢材编号','F','APGCTXP','FormXSCKBILLMLRHZB',0,'1','01','16','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','FormXSCKBILLMLRHZB',0,'1','02','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '12','钢材规格','F','APGCTXP','FormXSCKBILLMLRHZB',0,'1','03','12','钢材规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDu', '10','长度','F','APGCTXP','FormXSCKBILLMLRHZB',0,'1','04','10','长度','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '10','产地D','F','APGCTXP','FormXSCKBILLMLRHZB',0,'1','05','10','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','FormXSCKBILLMLRHZB',0,'1','06','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '4','单位','F','APGCTXP','FormXSCKBILLMLRHZB',0,'1','07','4','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'XSAMT', '10','销售金额','F','APGCTXP','FormXSCKBILLMLRHZB',0,'1','08','10','销售金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'XSCBAMT', '10','销售成本','F','APGCTXP','FormXSCKBILLMLRHZB',0,'1','09','10','销售成本','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MLRAMT', '10','销售毛利','F','APGCTXP','FormXSCKBILLMLRHZB',0,'1','10','10','销售毛利','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MLV', '10','销售毛利率','F','APGCTXP','FormXSCKBILLMLRHZB',0,'1','11','10','销售毛利率','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '20','自定义列1','F','APGCTXP','FormXSCKBILLMLRHZB',0,'1','12','20','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '20','自定义列2','F','APGCTXP','FormXSCKBILLMLRHZB',0,'1','13','20','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CLIENTName', '20','客户名称','F','APGCTXP','FormXSMXB',0,'1','01','20','客户名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'EMPNAME', '10','业务员','F','APGCTXP','FormXSMXB',0,'1','02','10','业务员','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STORENAME', '8','仓库名称','F','APGCTXP','FormXSMXB',0,'1','03','8','仓库名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CODE', '20','单据号','F','APGCTXP','FormXSMXB',0,'1','04','20','单据号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'BILLDATE', '10','单据日期','F','APGCTXP','FormXSMXB',0,'1','05','10','单据日期','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'OLDBILLCODE', '10','原始单号','F','APGCTXP','FormXSMXB',0,'1','06','10','原始单号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GoodsCode', '10','钢材编号','F','APGCTXP','FormXSMXB',0,'1','07','10','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','FormXSMXB',0,'1','08','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '12','规格','F','APGCTXP','FormXSMXB',0,'1','09','12','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDu', '10','长度','F','APGCTXP','FormXSMXB',0,'1','10','10','长度','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChanDi', '10','产地','F','APGCTXP','FormXSMXB',0,'1','11','10','产地','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CaiZhi', '10','材质','F','APGCTXP','FormXSMXB',0,'1','12','10','材质','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '10','产地D','F','APGCTXP','FormXSMXB',0,'1','13','10','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','FormXSMXB',0,'1','14','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '10','数量','F','APGCTXP','FormXSMXB',0,'1','15','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '4','单位','F','APGCTXP','FormXSMXB',0,'1','16','4','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'FuZhuQTY', '16','辅助数量','F','APGCTXP','FormXSMXB',0,'1','17','16','辅助数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '12','重量(吨)','F','APGCTXP','FormXSMXB',0,'1','18','12','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'PRICETYPENAME', '6','计价类别','F','APGCTXP','FormXSMXB',0,'1','19','6','计价类别','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITPRICE', '10','单价','F','APGCTXP','FormXSMXB',0,'1','20','10','单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'DISC', '10','折扣比率','F','APGCTXP','FormXSMXB',0,'1','21','10','折扣比率','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '12','金额','F','APGCTXP','FormXSMXB',0,'1','22','12','金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXRATE', '10','税率','F','APGCTXP','FormXSMXB',0,'1','23','10','税率','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'taxprice', '10','含税价','F','APGCTXP','FormXSMXB',0,'1','24','10','含税价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXJIN', '10','税金','F','APGCTXP','FormXSMXB',0,'1','25','10','税金','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXAMT', '10','价税合计','F','APGCTXP','FormXSMXB',0,'1','26','10','价税合计','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '20','自定义列1','F','APGCTXP','FormXSMXB',0,'1','27','20','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '20','自定义列2','F','APGCTXP','FormXSMXB',0,'1','28','20','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SpecNameD', '20','规格D','F','APGCTXP','FormXSMXB',0,'1','29','20','规格D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'BILLDATE', '10','单据日期','F','APGCTXP','FormYunShuQingDan',0,'1','01','10','单据日期','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'YunShuDWName', '20','运输单位','F','APGCTXP','FormYunShuQingDan',0,'1','02','20','运输单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CarNO', '10','车号','F','APGCTXP','FormYunShuQingDan',0,'1','03','10','车号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GoodsCode', '10','钢材编号','F','APGCTXP','FormYunShuQingDan',0,'1','04','10','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','FormYunShuQingDan',0,'1','05','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '12','规格','F','APGCTXP','FormYunShuQingDan',0,'1','06','12','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质','F','APGCTXP','FormYunShuQingDan',0,'0','07','10','材质','0')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '10','产地','F','APGCTXP','FormYunShuQingDan',0,'0','08','10','产地','0')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '4','单位','F','APGCTXP','FormYunShuQingDan',0,'1','09','4','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '12','运输数量','F','APGCTXP','FormYunShuQingDan',0,'1','10','12','运输数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'YunFeiPrice', '10','运输单价','F','APGCTXP','FormYunShuQingDan',0,'1','11','10','运输单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '10','运输金额','F','APGCTXP','FormYunShuQingDan',0,'1','12','10','运输金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'BILLTYPEName', '10','业务类型','F','APGCTXP','FormYunShuQingDan',0,'1','13','10','业务类型','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'OLDBILLCODE', '10','原始单号','F','APGCTXP','FormYunShuQingDan',0,'1','14','10','原始单号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CODE', '20','单据号','F','APGCTXP','FormYunShuQingDan',0,'1','15','20','单据号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '20','自定义列1','F','APGCTXP','FormYunShuQingDan',0,'0','16','20','自定义列1','0')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '20','自定义列2','F','APGCTXP','FormYunShuQingDan',0,'0','17','20','自定义列2','0')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ClientName', '30','客户名称','F','APGCTXP','FormYunShuQingDan',0,'1','18','30','客户名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'VendorName', '30','供应商名称','F','APGCTXP','FormYunShuQingDan',0,'1','19','30','供应商名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GoodsCode', '16','钢材编码','F','APGCTXP','FormZGRKYLB',0,'1','01','16','钢材编码','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','FormZGRKYLB',0,'1','02','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '12','规格','F','APGCTXP','FormZGRKYLB',0,'1','03','12','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质','F','APGCTXP','FormZGRKYLB',0,'0','04','10','材质','0')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '10','产地','F','APGCTXP','FormZGRKYLB',0,'0','05','10','产地','0')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '4','单位','F','APGCTXP','FormZGRKYLB',0,'1','06','4','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STORENAME', '10','仓库名称','F','APGCTXP','FormZGRKYLB',0,'1','07','10','仓库名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'VENDORNAME', '20','供应商','F','APGCTXP','FormZGRKYLB',0,'1','08','20','供应商','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '12','在估重量(吨)','F','APGCTXP','FormZGRKYLB',0,'1','09','12','在估重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '12','在估金额','F','APGCTXP','FormZGRKYLB',0,'1','10','12','在估金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '20','自定义列1','F','APGCTXP','FormZGRKYLB',0,'0','11','20','自定义列1','0')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '20','自定义列2','F','APGCTXP','FormZGRKYLB',0,'0','12','20','自定义列2','0')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'T', '6','T','F','APGCTXP','STORECGDDM',0,'1','01','6','T','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STOREID', '12','仓库编码','F','APGCTXP','STORECGDDM',0,'1','02','12','仓库编码','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STORENAME', '16','仓库名称','F','APGCTXP','STORECGDDM',0,'1','03','16','仓库名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSID', '10','钢材编号','F','APGCTXP','STORECGDDM',0,'1','04','10','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','STORECGDDM',0,'1','05','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '16','规格','F','APGCTXP','STORECGDDM',0,'1','06','16','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDuMi', '10','长度(米)','F','APGCTXP','STORECGDDM',0,'1','07','10','长度(米)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChanDi', '10','产地','F','APGCTXP','STORECGDDM',0,'1','08','10','产地','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CaiZhi', '10','材质','F','APGCTXP','STORECGDDM',0,'1','09','10','材质','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '6','产地D','F','APGCTXP','STORECGDDM',0,'1','10','6','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '6','材质D','F','APGCTXP','STORECGDDM',0,'1','11','6','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'JianShu', '10','件数','F','APGCTXP','STORECGDDM',0,'1','12','10','件数','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'Rate1', '10','每件数量','F','APGCTXP','STORECGDDM',0,'1','13','10','每件数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LingTou', '10','零头','F','APGCTXP','STORECGDDM',0,'1','14','10','零头','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '10','数量','F','APGCTXP','STORECGDDM',0,'1','15','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '5','单位','F','APGCTXP','STORECGDDM',0,'1','16','5','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'FuZhuQTY', '16','辅助数量','T','APGCTXP','STORECGDDM',0,'1','17','16','辅助数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '10','重量(吨)','F','APGCTXP','STORECGDDM',0,'1','18','10','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LSRATE', '10','理算系数','T','APGCTXP','STORECGDDM',0,'1','19','10','理算系数','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LLZhongLiang', '10','理论重量(吨)','T','APGCTXP','STORECGDDM',0,'1','20','10','理论重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITPRICE', '10','单价','F','APGCTXP','STORECGDDM',0,'1','21','10','单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'PRICETYPENAME', '8','计价类别','F','APGCTXP','STORECGDDM',0,'1','22','8','计价类别','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'DISC', '6','折扣比率','F','APGCTXP','STORECGDDM',0,'1','23','6','折扣比率','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXRATE', '6','税率','F','APGCTXP','STORECGDDM',0,'1','24','6','税率','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXJIN', '6','税金','F','APGCTXP','STORECGDDM',0,'1','25','6','税金','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '8','货款金额','F','APGCTXP','STORECGDDM',0,'1','26','8','货款金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXAMT', '10','价税合计','F','APGCTXP','STORECGDDM',0,'1','27','10','价税合计','1')
----------ENDFLAG
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'YunFeiFT', '10','运费分摊','F','APGCTXP','STORECGDDM',0,'1','28','10','运费分摊','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MEMO', '20','备注','F','APGCTXP','STORECGDDM',0,'1','29','20','备注','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'REGJRKCODE', '16','估价入库单号','T','APGCTXP','STORECGDDM',0,'1','30','16','估价入库单号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '50','自定义列1','F','APGCTXP','STORECGDDM',0,'1','31','50','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '50','自定义列2','F','APGCTXP','STORECGDDM',0,'1','32','50','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MiZhong', '10','米重(公斤)','F','APGCTXP','STORECGDDM',0,'1','33','10','米重(公斤)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ZongLen', '10','总长度(米)','F','APGCTXP','STORECGDDM',0,'1','34','10','总长度(米)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'T', '6','T','F','APGCTXP','STORECGRKM',0,'1','01','6','T','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STOREID', '12','仓库编码','F','APGCTXP','STORECGRKM',0,'1','02','12','仓库编码','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STORENAME', '16','仓库名称','F','APGCTXP','STORECGRKM',0,'1','03','16','仓库名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSID', '10','钢材编号','F','APGCTXP','STORECGRKM',0,'1','04','10','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','STORECGRKM',0,'1','05','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '16','规格','F','APGCTXP','STORECGRKM',0,'1','06','16','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDuMi', '10','长度(米)','F','APGCTXP','STORECGRKM',0,'1','07','10','长度(米)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChanDi', '10','产地','F','APGCTXP','STORECGRKM',0,'1','08','10','产地','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CaiZhi', '10','材质','F','APGCTXP','STORECGRKM',0,'1','09','10','材质','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '6','产地D','F','APGCTXP','STORECGRKM',0,'1','10','6','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '6','材质D','F','APGCTXP','STORECGRKM',0,'1','11','6','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'JianShu', '10','件数','F','APGCTXP','STORECGRKM',0,'1','12','10','件数','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'Rate1', '10','每件数量','F','APGCTXP','STORECGRKM',0,'1','13','10','每件数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LingTou', '10','零头','F','APGCTXP','STORECGRKM',0,'1','14','10','零头','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '10','数量','F','APGCTXP','STORECGRKM',0,'1','15','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '5','单位','F','APGCTXP','STORECGRKM',0,'1','16','5','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'FuZhuQTY', '16','辅助数量','T','APGCTXP','STORECGRKM',0,'1','17','16','辅助数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '10','重量(吨)','F','APGCTXP','STORECGRKM',0,'1','18','10','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LSRATE', '10','理算系数','T','APGCTXP','STORECGRKM',0,'1','19','10','理算系数','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LLZhongLiang', '10','理论重量(吨)','T','APGCTXP','STORECGRKM',0,'1','20','10','理论重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITPRICE', '10','单价','F','APGCTXP','STORECGRKM',0,'1','21','10','单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'PRICETYPENAME', '8','计价类别','F','APGCTXP','STORECGRKM',0,'1','22','8','计价类别','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'DISC', '6','折扣比率','F','APGCTXP','STORECGRKM',0,'1','23','6','折扣比率','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXRATE', '6','税率','F','APGCTXP','STORECGRKM',0,'1','24','6','税率','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXJIN', '6','税金','F','APGCTXP','STORECGRKM',0,'1','25','6','税金','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '8','货款金额','F','APGCTXP','STORECGRKM',0,'1','26','8','货款金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXAMT', '10','价税合计','F','APGCTXP','STORECGRKM',0,'1','27','10','价税合计','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'YunFeiFT', '10','运费分摊','F','APGCTXP','STORECGRKM',0,'1','28','10','运费分摊','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MEMO', '20','备注','F','APGCTXP','STORECGRKM',0,'1','29','20','备注','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '50','自定义列1','F','APGCTXP','STORECGRKM',0,'1','30','50','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '50','自定义列2','F','APGCTXP','STORECGRKM',0,'1','31','50','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MiZhong', '10','米重(公斤)','F','APGCTXP','STORECGRKM',0,'1','32','10','米重(公斤)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ZongLen', '10','总长度(米)','F','APGCTXP','STORECGRKM',0,'1','33','10','总长度(米)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'T', '6','T','F','APGCTXP','STORECGTHM',0,'1','01','6','T','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STOREID', '12','仓库编码','F','APGCTXP','STORECGTHM',0,'1','02','12','仓库编码','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STORENAME', '16','仓库名称','F','APGCTXP','STORECGTHM',0,'1','03','16','仓库名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSID', '10','钢材编号','F','APGCTXP','STORECGTHM',0,'1','04','10','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','STORECGTHM',0,'1','05','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '16','规格','F','APGCTXP','STORECGTHM',0,'1','06','16','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDu', '10','长度','F','APGCTXP','STORECGTHM',0,'1','07','10','长度','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChanDi', '10','产地','F','APGCTXP','STORECGTHM',0,'1','08','10','产地','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CaiZhi', '10','材质','F','APGCTXP','STORECGTHM',0,'1','09','10','材质','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '6','产地D','F','APGCTXP','STORECGTHM',0,'1','10','6','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','STORECGTHM',0,'1','11','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'JianShu', '10','件数','F','APGCTXP','STORECGTHM',0,'1','12','10','件数','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'Rate1', '10','每件数量','F','APGCTXP','STORECGTHM',0,'1','13','10','每件数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LingTou', '10','零头','F','APGCTXP','STORECGTHM',0,'1','14','10','零头','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '10','数量','F','APGCTXP','STORECGTHM',0,'1','15','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '5','单位','F','APGCTXP','STORECGTHM',0,'1','16','5','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'FuZhuQTY', '16','辅助数量','T','APGCTXP','STORECGTHM',0,'1','17','16','辅助数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '10','重量(吨)','F','APGCTXP','STORECGTHM',0,'1','18','10','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LSRATE', '10','理算系数','T','APGCTXP','STORECGTHM',0,'1','19','10','理算系数','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LLZhongLiang', '10','理论重量(吨)','T','APGCTXP','STORECGTHM',0,'1','20','10','理论重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITPRICE', '10','单价','F','APGCTXP','STORECGTHM',0,'1','21','10','单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'PRICETYPENAME', '8','计价类别','F','APGCTXP','STORECGTHM',0,'1','22','8','计价类别','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'DISC', '6','折扣比率','F','APGCTXP','STORECGTHM',0,'1','23','6','折扣比率','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXRATE', '6','税率','F','APGCTXP','STORECGTHM',0,'1','24','6','税率','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXJIN', '6','税金','F','APGCTXP','STORECGTHM',0,'1','25','6','税金','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '8','货款金额','F','APGCTXP','STORECGTHM',0,'1','26','8','货款金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXAMT', '10','价税合计','F','APGCTXP','STORECGTHM',0,'1','27','10','价税合计','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MEMO', '20','备注','F','APGCTXP','STORECGTHM',0,'1','28','20','备注','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '50','自定义列1','F','APGCTXP','STORECGTHM',0,'1','29','50','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '50','自定义列2','F','APGCTXP','STORECGTHM',0,'1','30','50','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'T', '6','T','F','APGCTXP','STORECKDBM',0,'1','01','6','T','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSID', '10','钢材编号','F','APGCTXP','STORECKDBM',0,'1','02','10','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','STORECKDBM',0,'1','03','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '16','钢材规格','F','APGCTXP','STORECKDBM',0,'1','04','16','钢材规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDu', '10','长度','F','APGCTXP','STORECKDBM',0,'1','05','10','长度','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChanDi', '10','产地','F','APGCTXP','STORECKDBM',0,'1','06','10','产地','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CaiZhi', '10','材质','F','APGCTXP','STORECKDBM',0,'1','07','10','材质','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '6','产地D','F','APGCTXP','STORECKDBM',0,'1','08','6','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','STORECKDBM',0,'1','09','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'JianShu', '10','件数','F','APGCTXP','STORECKDBM',0,'1','10','10','件数','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'Rate1', '10','每件数量','F','APGCTXP','STORECKDBM',0,'1','11','10','每件数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LingTou', '10','零头','F','APGCTXP','STORECKDBM',0,'1','12','10','零头','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '10','数量','F','APGCTXP','STORECKDBM',0,'1','13','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '5','单位','F','APGCTXP','STORECKDBM',0,'1','14','5','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'FuZhuQTY', '16','辅助数量','T','APGCTXP','STORECKDBM',0,'1','15','16','辅助数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '10','重量(吨)','F','APGCTXP','STORECKDBM',0,'1','16','10','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LSRATE', '10','理算系数','T','APGCTXP','STORECKDBM',0,'1','17','10','理算系数','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LLZhongLiang', '10','理论重量(吨)','T','APGCTXP','STORECKDBM',0,'1','18','10','理论重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'PRICETYPENAME', '6','计价类别','F','APGCTXP','STORECKDBM',0,'1','19','6','计价类别','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITPRICE', '10','单价','T','APGCTXP','STORECKDBM',0,'1','20','10','单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '10','金额','F','APGCTXP','STORECKDBM',0,'1','21','10','金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MEMO', '20','备注','F','APGCTXP','STORECKDBM',0,'1','22','20','备注','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '50','自定义列1','F','APGCTXP','STORECKDBM',0,'1','23','50','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '50','自定义列2','F','APGCTXP','STORECKDBM',0,'1','24','50','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STOREID', '8','仓库名称','F','APGCTXP','STORECKPDM',0,'1','01','8','仓库名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSID', '10','钢材编号','F','APGCTXP','STORECKPDM',0,'1','02','10','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','STORECKPDM',0,'1','03','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '16','规格','F','APGCTXP','STORECKPDM',0,'1','04','16','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDu', '10','长度','F','APGCTXP','STORECKPDM',0,'1','05','10','长度','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChanDi', '10','产地','F','APGCTXP','STORECKPDM',0,'1','06','10','产地','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CaiZhi', '10','材质','F','APGCTXP','STORECKPDM',0,'1','07','10','材质','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '10','产地D','F','APGCTXP','STORECKPDM',0,'1','08','10','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','STORECKPDM',0,'1','09','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '8','实盘数量','F','APGCTXP','STORECKPDM',0,'1','10','8','实盘数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITPRICE', '8','帐面数量','T','APGCTXP','STORECKPDM',0,'1','11','8','帐面数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MYKQTY', '8','盈亏数量','F','APGCTXP','STORECKPDM',0,'1','12','8','盈亏数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '4','单位','F','APGCTXP','STORECKPDM',0,'1','13','4','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '8','实盘(吨)','F','APGCTXP','STORECKPDM',0,'1','14','8','实盘(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LSRATE', '10','理算系数','T','APGCTXP','STORECKPDM',0,'1','15','10','理算系数','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LLZhongLiang', '10','理论重量(吨)','T','APGCTXP','STORECKPDM',0,'1','16','10','理论重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'PRICE', '8','帐面(吨)','T','APGCTXP','STORECKPDM',0,'1','17','8','帐面(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'YKQTY', '8','盈亏(吨)','F','APGCTXP','STORECKPDM',0,'1','18','8','盈亏(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MEMO', '20','备注','F','APGCTXP','STORECKPDM',0,'1','19','20','备注','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '50','自定义列1','F','APGCTXP','STORECKPDM',0,'1','20','50','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '50','自定义列2','F','APGCTXP','STORECKPDM',0,'1','21','50','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'T', '6','T','F','APGCTXP','STORECSHM',0,'1','01','6','T','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STOREID', '8','仓库编码','F','APGCTXP','STORECSHM',0,'1','02','8','仓库编码','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STORENAME', '12','仓库名称','F','APGCTXP','STORECSHM',0,'1','03','12','仓库名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSID', '10','钢材编号','F','APGCTXP','STORECSHM',0,'1','04','10','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','STORECSHM',0,'1','05','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '16','规格','F','APGCTXP','STORECSHM',0,'1','06','16','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDu', '10','长度','F','APGCTXP','STORECSHM',0,'1','07','10','长度','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChanDi', '10','产地','F','APGCTXP','STORECSHM',0,'1','08','10','产地','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CaiZhi', '10','材质','F','APGCTXP','STORECSHM',0,'1','09','10','材质','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '6','产地D','F','APGCTXP','STORECSHM',0,'1','10','6','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '8','材质D','F','APGCTXP','STORECSHM',0,'1','11','8','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'JianShu', '10','件数','F','APGCTXP','STORECSHM',0,'1','12','10','件数','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'Rate1', '10','每件数量','F','APGCTXP','STORECSHM',0,'1','13','10','每件数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LingTou', '10','零头','F','APGCTXP','STORECSHM',0,'1','14','10','零头','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '10','数量','F','APGCTXP','STORECSHM',0,'1','15','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '5','单位','F','APGCTXP','STORECSHM',0,'1','16','5','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'FuZhuQTY', '16','辅助数量','T','APGCTXP','STORECSHM',0,'1','17','16','辅助数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '10','重量(吨)','F','APGCTXP','STORECSHM',0,'1','18','10','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'PRICETYPENAME', '8','计价类别','F','APGCTXP','STORECSHM',0,'1','19','8','计价类别','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITPRICE', '10','单价','F','APGCTXP','STORECSHM',0,'1','20','10','单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '10','金额','F','APGCTXP','STORECSHM',0,'1','21','10','金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MEMO', '20','备注','F','APGCTXP','STORECSHM',0,'1','22','20','备注','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '50','自定义列1','F','APGCTXP','STORECSHM',0,'1','23','50','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '50','自定义列2','F','APGCTXP','STORECSHM',0,'1','24','50','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STOREID', '8','仓库名称','F','APGCTXP','STOREJGDM',0,'1','01','8','仓库名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSID', '10','钢材编号','F','APGCTXP','STOREJGDM',0,'1','02','10','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','STOREJGDM',0,'1','03','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '16','规格','F','APGCTXP','STOREJGDM',0,'1','04','16','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDu', '10','长度','F','APGCTXP','STOREJGDM',0,'1','05','10','长度','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChanDi', '10','产地','F','APGCTXP','STOREJGDM',0,'1','06','10','产地','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CaiZhi', '10','材质','F','APGCTXP','STOREJGDM',0,'1','07','10','材质','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '6','产地D','F','APGCTXP','STOREJGDM',0,'1','08','6','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','STOREJGDM',0,'1','09','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '10','数量','F','APGCTXP','STOREJGDM',0,'1','10','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '5','单位','F','APGCTXP','STOREJGDM',0,'1','11','5','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '10','重量(吨)','F','APGCTXP','STOREJGDM',0,'1','12','10','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LSRATE', '10','理算系数','T','APGCTXP','STOREJGDM',0,'1','13','10','理算系数','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LLZhongLiang', '10','理论重量(吨)','T','APGCTXP','STOREJGDM',0,'1','14','10','理论重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'PRICETYPENAME', '8','计价类别','F','APGCTXP','STOREJGDM',0,'1','15','8','计价类别','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITPRICE', '10','单价','F','APGCTXP','STOREJGDM',0,'1','16','10','单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '8','金额','F','APGCTXP','STOREJGDM',0,'1','17','8','金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MEMO', '20','备注','F','APGCTXP','STOREJGDM',0,'1','18','20','备注','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '50','自定义列1','F','APGCTXP','STOREJGDM',0,'1','19','50','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '50','自定义列2','F','APGCTXP','STOREJGDM',0,'1','20','50','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STOREID', '12','仓库编码','F','APGCTXP','STORELiuHM',0,'1','01','12','仓库编码','1')
----------ENDFLAG
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STORENAME', '16','仓库名称','F','APGCTXP','STORELiuHM',0,'1','02','16','仓库名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSID', '10','钢材编号','F','APGCTXP','STORELiuHM',0,'1','03','10','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','STORELiuHM',0,'1','04','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '16','规格','F','APGCTXP','STORELiuHM',0,'1','05','16','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SpecNameD', '16','规格D','F','APGCTXP','STORELiuHM',0,'1','06','16','规格D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDu', '10','长度','F','APGCTXP','STORELiuHM',0,'1','07','10','长度','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChanDi', '10','产地','F','APGCTXP','STORELiuHM',0,'1','08','10','产地','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CaiZhi', '10','材质','F','APGCTXP','STORELiuHM',0,'1','09','10','材质','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '6','产地D','F','APGCTXP','STORELiuHM',0,'1','10','6','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','STORELiuHM',0,'1','11','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '10','数量','F','APGCTXP','STORELiuHM',0,'1','12','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '5','单位','F','APGCTXP','STORELiuHM',0,'1','13','5','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '10','重量(吨)','F','APGCTXP','STORELiuHM',0,'1','14','10','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LSRATE', '10','理算系数','T','APGCTXP','STORELiuHM',0,'1','15','10','理算系数','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LLZhongLiang', '10','理论重量(吨)','T','APGCTXP','STORELiuHM',0,'1','16','10','理论重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITPRICE', '10','单价','F','APGCTXP','STORELiuHM',0,'1','17','10','单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'PRICETYPENAME', '8','计价类别','F','APGCTXP','STORELiuHM',0,'1','18','8','计价类别','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'DISC', '6','折扣比率','F','APGCTXP','STORELiuHM',0,'1','19','6','折扣比率','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXRATE', '6','税率','F','APGCTXP','STORELiuHM',0,'1','20','6','税率','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXJIN', '6','税金','F','APGCTXP','STORELiuHM',0,'1','21','6','税金','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '8','货款金额','F','APGCTXP','STORELiuHM',0,'1','22','8','货款金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXAMT', '10','价税合计','F','APGCTXP','STORELiuHM',0,'1','23','10','价税合计','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'YunFeiFT', '10','运费分摊','F','APGCTXP','STORELiuHM',0,'1','24','10','运费分摊','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MEMO', '20','备注','F','APGCTXP','STORELiuHM',0,'1','25','20','备注','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '50','自定义列1','F','APGCTXP','STORELiuHM',0,'1','26','50','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '50','自定义列2','F','APGCTXP','STORELiuHM',0,'1','27','50','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STOREID', '12','完工仓库编码','F','APGCTXP','STOREQGADM',0,'1','01','12','完工仓库编码','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STORENAME', '16','完工仓库名称','F','APGCTXP','STOREQGADM',0,'1','02','16','完工仓库名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSID', '10','钢材编号','F','APGCTXP','STOREQGADM',0,'1','03','10','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','STOREQGADM',0,'1','04','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '16','规格','F','APGCTXP','STOREQGADM',0,'1','05','16','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDu', '10','长度','F','APGCTXP','STOREQGADM',0,'1','06','10','长度','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChanDi', '10','产地','F','APGCTXP','STOREQGADM',0,'1','07','10','产地','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CaiZhi', '10','材质','F','APGCTXP','STOREQGADM',0,'1','08','10','材质','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '6','产地D','F','APGCTXP','STOREQGADM',0,'1','09','6','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','STOREQGADM',0,'1','10','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '10','数量','F','APGCTXP','STOREQGADM',0,'1','11','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '5','单位','F','APGCTXP','STOREQGADM',0,'1','12','5','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '10','重量(吨)','F','APGCTXP','STOREQGADM',0,'1','13','10','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LSRATE', '10','理算系数','T','APGCTXP','STOREQGADM',0,'1','14','10','理算系数','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LLZhongLiang', '10','理论重量(吨)','T','APGCTXP','STOREQGADM',0,'1','15','10','理论重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'PRICETYPENAME', '8','计价类别','F','APGCTXP','STOREQGADM',0,'1','16','8','计价类别','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITPRICE', '10','单价','F','APGCTXP','STOREQGADM',0,'1','17','10','单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '8','金额','F','APGCTXP','STOREQGADM',0,'1','18','8','金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MEMO', '20','备注','F','APGCTXP','STOREQGADM',0,'1','19','20','备注','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '50','自定义列1','F','APGCTXP','STOREQGADM',0,'1','20','50','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '50','自定义列2','F','APGCTXP','STOREQGADM',0,'1','21','50','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'T', '6','T','F','APGCTXP','STOREQTCKM',0,'1','01','6','T','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STOREID', '12','仓库编码','F','APGCTXP','STOREQTCKM',0,'1','02','12','仓库编码','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STORENAME', '16','仓库名称','F','APGCTXP','STOREQTCKM',0,'1','03','16','仓库名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSID', '10','钢材编号','F','APGCTXP','STOREQTCKM',0,'1','04','10','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','STOREQTCKM',0,'1','05','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '16','规格','F','APGCTXP','STOREQTCKM',0,'1','06','16','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDu', '10','长度','F','APGCTXP','STOREQTCKM',0,'1','07','10','长度','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChanDi', '10','产地','F','APGCTXP','STOREQTCKM',0,'1','08','10','产地','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CaiZhi', '10','材质','F','APGCTXP','STOREQTCKM',0,'1','09','10','材质','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '6','产地D','F','APGCTXP','STOREQTCKM',0,'1','10','6','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','STOREQTCKM',0,'1','11','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'JianShu', '10','件数','F','APGCTXP','STOREQTCKM',0,'1','12','10','件数','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'Rate1', '10','每件数量','F','APGCTXP','STOREQTCKM',0,'1','13','10','每件数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LingTou', '10','零头','F','APGCTXP','STOREQTCKM',0,'1','14','10','零头','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '10','数量','F','APGCTXP','STOREQTCKM',0,'1','15','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '5','单位','F','APGCTXP','STOREQTCKM',0,'1','16','5','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'FuZhuQTY', '16','辅助数量','T','APGCTXP','STOREQTCKM',0,'1','17','16','辅助数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '10','重量(吨)','F','APGCTXP','STOREQTCKM',0,'1','18','10','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LSRATE', '10','理算系数','T','APGCTXP','STOREQTCKM',0,'1','19','10','理算系数','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LLZhongLiang', '10','理论重量(吨)','T','APGCTXP','STOREQTCKM',0,'1','20','10','理论重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'PRICETYPENAME', '6','计价类别','F','APGCTXP','STOREQTCKM',0,'1','21','6','计价类别','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITPRICE', '10','单价','F','APGCTXP','STOREQTCKM',0,'1','22','10','单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '12','金额','F','APGCTXP','STOREQTCKM',0,'1','23','12','金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MEMO', '20','备注','F','APGCTXP','STOREQTCKM',0,'1','24','20','备注','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '50','自定义列1','F','APGCTXP','STOREQTCKM',0,'1','25','50','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '50','自定义列2','F','APGCTXP','STOREQTCKM',0,'1','26','50','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'T', '6','T','F','APGCTXP','STOREQTRKM',0,'1','01','6','T','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STOREID', '12','仓库编码','F','APGCTXP','STOREQTRKM',0,'1','02','12','仓库编码','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STORENAME', '16','仓库名称','F','APGCTXP','STOREQTRKM',0,'1','03','16','仓库名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSID', '10','钢材编号','F','APGCTXP','STOREQTRKM',0,'1','04','10','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','STOREQTRKM',0,'1','05','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '16','规格','F','APGCTXP','STOREQTRKM',0,'1','06','16','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDu', '10','长度','F','APGCTXP','STOREQTRKM',0,'1','07','10','长度','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChanDi', '10','产地','F','APGCTXP','STOREQTRKM',0,'1','08','10','产地','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CaiZhi', '10','材质','F','APGCTXP','STOREQTRKM',0,'1','09','10','材质','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '6','产地D','F','APGCTXP','STOREQTRKM',0,'1','10','6','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','STOREQTRKM',0,'1','11','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'JianShu', '10','件数','F','APGCTXP','STOREQTRKM',0,'1','12','10','件数','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'Rate1', '10','每件数量','F','APGCTXP','STOREQTRKM',0,'1','13','10','每件数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LingTou', '10','零头','F','APGCTXP','STOREQTRKM',0,'1','14','10','零头','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '10','数量','F','APGCTXP','STOREQTRKM',0,'1','15','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '5','单位','F','APGCTXP','STOREQTRKM',0,'1','16','5','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'FuZhuQTY', '16','辅助数量','T','APGCTXP','STOREQTRKM',0,'1','17','16','辅助数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '10','重量(吨)','F','APGCTXP','STOREQTRKM',0,'1','18','10','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LSRATE', '10','理算系数','T','APGCTXP','STOREQTRKM',0,'1','19','10','理算系数','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LLZhongLiang', '10','理论重量(吨)','T','APGCTXP','STOREQTRKM',0,'1','20','10','理论重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'PRICETYPENAME', '8','计价类别','F','APGCTXP','STOREQTRKM',0,'1','21','8','计价类别','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITPRICE', '10','单价','F','APGCTXP','STOREQTRKM',0,'1','22','10','单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '12','金额','F','APGCTXP','STOREQTRKM',0,'1','23','12','金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MEMO', '20','备注','F','APGCTXP','STOREQTRKM',0,'1','24','20','备注','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '50','自定义列1','F','APGCTXP','STOREQTRKM',0,'1','25','50','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '50','自定义列2','F','APGCTXP','STOREQTRKM',0,'1','26','50','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'T', '6','T','F','APGCTXP','STOREXSCKM',0,'1','01','6','T','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STOREID', '12','仓库编码','F','APGCTXP','STOREXSCKM',0,'1','02','12','仓库编码','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STORENAME', '16','仓库名称','F','APGCTXP','STOREXSCKM',0,'1','03','16','仓库名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSID', '10','钢材编号','F','APGCTXP','STOREXSCKM',0,'1','04','10','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','STOREXSCKM',0,'1','05','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '16','规格','F','APGCTXP','STOREXSCKM',0,'1','06','16','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SpecNameD', '16','规格D','F','APGCTXP','STOREXSCKM',0,'0','07','16','规格D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDuMi', '10','长度(米)','F','APGCTXP','STOREXSCKM',0,'0','08','10','长度(米)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChanDi', '10','产地','F','APGCTXP','STOREXSCKM',0,'0','09','10','产地','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CaiZhi', '10','材质','F','APGCTXP','STOREXSCKM',0,'0','10','10','材质','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '6','产地D','F','APGCTXP','STOREXSCKM',0,'0','11','6','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','STOREXSCKM',0,'0','12','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'JianShu', '10','件数','F','APGCTXP','STOREXSCKM',0,'0','13','10','件数','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'Rate1', '10','每件数量','F','APGCTXP','STOREXSCKM',0,'0','14','10','每件数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LingTou', '10','零头','F','APGCTXP','STOREXSCKM',0,'0','15','10','零头','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '10','数量','F','APGCTXP','STOREXSCKM',0,'1','16','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '5','单位','F','APGCTXP','STOREXSCKM',0,'1','17','5','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'FuZhuQTY', '16','辅助数量','T','APGCTXP','STOREXSCKM',0,'0','18','16','辅助数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '10','重量(吨)','F','APGCTXP','STOREXSCKM',0,'1','19','10','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LSRATE', '10','理算系数','T','APGCTXP','STOREXSCKM',0,'1','20','10','理算系数','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LLZhongLiang', '10','理论重量(吨)','T','APGCTXP','STOREXSCKM',0,'1','21','10','理论重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITPRICE', '10','单价','F','APGCTXP','STOREXSCKM',0,'1','22','10','单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'PRICETYPENAME', '8','计价类别','F','APGCTXP','STOREXSCKM',0,'1','23','8','计价类别','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'DISC', '6','折扣比率','F','APGCTXP','STOREXSCKM',0,'1','24','6','折扣比率','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXRATE', '6','税率','F','APGCTXP','STOREXSCKM',0,'1','25','6','税率','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXJIN', '6','税金','F','APGCTXP','STOREXSCKM',0,'1','26','6','税金','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '8','货款金额','F','APGCTXP','STOREXSCKM',0,'1','27','8','货款金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXAMT', '10','价税合计','F','APGCTXP','STOREXSCKM',0,'1','28','10','价税合计','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'YunFeiFT', '10','运费分摊','F','APGCTXP','STOREXSCKM',0,'1','29','10','运费分摊','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MEMO', '20','备注','F','APGCTXP','STOREXSCKM',0,'1','30','20','备注','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '50','自定义列1','F','APGCTXP','STOREXSCKM',0,'1','31','50','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '50','自定义列2','F','APGCTXP','STOREXSCKM',0,'1','32','50','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'DXSPrice', '10','销售价(吨)','F','APGCTXP','STOREXSCKM',0,'1','33','10','销售价(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MXSPrice', '10','销售价(数量)','F','APGCTXP','STOREXSCKM',0,'1','34','10','销售价(数量)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MiZhong', '10','米重(公斤)','F','APGCTXP','STOREXSCKM',0,'1','35','10','米重(公斤)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ZongLen', '10','总长(米)','F','APGCTXP','STOREXSCKM',0,'1','36','10','总长(米)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'T', '6','T','F','APGCTXP','STOREXSDDM',0,'1','01','6','T','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STOREID', '12','仓库编码','F','APGCTXP','STOREXSDDM',0,'1','02','12','仓库编码','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STORENAME', '16','仓库名称','F','APGCTXP','STOREXSDDM',0,'1','03','16','仓库名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSID', '10','钢材编号','F','APGCTXP','STOREXSDDM',0,'1','04','10','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','STOREXSDDM',0,'1','05','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '16','规格','F','APGCTXP','STOREXSDDM',0,'1','06','16','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SpecNameD', '16','规格D','F','APGCTXP','STOREXSDDM',0,'1','07','16','规格D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDuMi', '10','长度(米)','F','APGCTXP','STOREXSDDM',0,'1','08','10','长度(米)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChanDi', '10','产地','F','APGCTXP','STOREXSDDM',0,'1','09','10','产地','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CaiZhi', '10','材质','F','APGCTXP','STOREXSDDM',0,'1','10','10','材质','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '6','产地D','F','APGCTXP','STOREXSDDM',0,'1','11','6','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','STOREXSDDM',0,'1','12','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'JianShu', '10','件数','F','APGCTXP','STOREXSDDM',0,'1','13','10','件数','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'Rate1', '10','每件数量','F','APGCTXP','STOREXSDDM',0,'1','14','10','每件数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LingTou', '10','零头','F','APGCTXP','STOREXSDDM',0,'1','15','10','零头','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '10','数量','F','APGCTXP','STOREXSDDM',0,'1','16','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '5','单位','F','APGCTXP','STOREXSDDM',0,'1','17','5','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'FuZhuQTY', '16','辅助数量','T','APGCTXP','STOREXSDDM',0,'1','18','16','辅助数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '10','重量(吨)','F','APGCTXP','STOREXSDDM',0,'1','19','10','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LSRATE', '10','理算系数','T','APGCTXP','STOREXSDDM',0,'1','20','10','理算系数','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LLZhongLiang', '10','理论重量(吨)','T','APGCTXP','STOREXSDDM',0,'1','21','10','理论重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITPRICE', '10','单价','F','APGCTXP','STOREXSDDM',0,'1','22','10','单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'PRICETYPENAME', '8','计价类别','F','APGCTXP','STOREXSDDM',0,'1','23','8','计价类别','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'DISC', '6','折扣比率','F','APGCTXP','STOREXSDDM',0,'1','24','6','折扣比率','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXRATE', '6','税率','F','APGCTXP','STOREXSDDM',0,'1','25','6','税率','1')
----------ENDFLAG
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXJIN', '6','税金','F','APGCTXP','STOREXSDDM',0,'1','26','6','税金','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '8','货款金额','F','APGCTXP','STOREXSDDM',0,'1','27','8','货款金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXAMT', '10','价税合计','F','APGCTXP','STOREXSDDM',0,'1','28','10','价税合计','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'YunFeiFT', '10','运费分摊','F','APGCTXP','STOREXSDDM',0,'1','29','10','运费分摊','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MEMO', '20','备注','F','APGCTXP','STOREXSDDM',0,'1','30','20','备注','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '50','自定义列1','F','APGCTXP','STOREXSDDM',0,'1','31','50','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '50','自定义列2','F','APGCTXP','STOREXSDDM',0,'1','32','50','自定义列2','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'DXSPrice', '10','销售价(吨)','F','APGCTXP','STOREXSDDM',0,'1','33','10','销售价(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MXSPrice', '10','销售价(数量)','F','APGCTXP','STOREXSDDM',0,'1','34','10','销售价(数量)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MiZhong', '10','米重(公斤)','F','APGCTXP','STOREXSDDM',0,'1','35','10','米重(公斤)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ZongLen', '10','总长度(米)','F','APGCTXP','STOREXSDDM',0,'1','36','10','总长度(米)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'T', '6','T','F','APGCTXP','STOREXSTHM',0,'1','01','6','T','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STOREID', '12','仓库编码','F','APGCTXP','STOREXSTHM',0,'1','02','12','仓库编码','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'STORENAME', '16','仓库名称','F','APGCTXP','STOREXSTHM',0,'1','03','16','仓库名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSID', '10','钢材编号','F','APGCTXP','STOREXSTHM',0,'1','04','10','钢材编号','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'GOODSNAME', '20','钢材名称','F','APGCTXP','STOREXSTHM',0,'1','05','20','钢材名称','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'SPECNAME', '16','规格','F','APGCTXP','STOREXSTHM',0,'1','06','16','规格','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChangDu', '10','长度','F','APGCTXP','STOREXSTHM',0,'1','07','10','长度','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'ChanDi', '10','产地','F','APGCTXP','STOREXSTHM',0,'1','08','10','产地','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'CaiZhi', '10','材质','F','APGCTXP','STOREXSTHM',0,'1','09','10','材质','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MAKEAREA', '6','产地D','F','APGCTXP','STOREXSTHM',0,'1','10','6','产地D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MODELNAME', '10','材质D','F','APGCTXP','STOREXSTHM',0,'1','11','10','材质D','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'JianShu', '10','件数','F','APGCTXP','STOREXSTHM',0,'1','12','10','件数','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'Rate1', '10','每件数量','F','APGCTXP','STOREXSTHM',0,'1','13','10','每件数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LingTou', '10','零头','F','APGCTXP','STOREXSTHM',0,'1','14','10','零头','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITQTY', '10','数量','F','APGCTXP','STOREXSTHM',0,'1','15','10','数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNIT', '5','单位','F','APGCTXP','STOREXSTHM',0,'1','16','5','单位','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'FuZhuQTY', '16','辅助数量','T','APGCTXP','STOREXSTHM',0,'1','17','16','辅助数量','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'QUANTITY', '10','重量(吨)','F','APGCTXP','STOREXSTHM',0,'1','18','10','重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LSRATE', '10','理算系数','T','APGCTXP','STOREXSTHM',0,'1','19','10','理算系数','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'LLZhongLiang', '10','理论重量(吨)','T','APGCTXP','STOREXSTHM',0,'1','20','10','理论重量(吨)','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'PRICETYPENAME', '8','计价类别','F','APGCTXP','STOREXSTHM',0,'1','21','8','计价类别','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'UNITPRICE', '10','单价','F','APGCTXP','STOREXSTHM',0,'1','22','10','单价','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'DISC', '6','折扣比率','F','APGCTXP','STOREXSTHM',0,'1','23','6','折扣比率','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXRATE', '6','税率','F','APGCTXP','STOREXSTHM',0,'1','24','6','税率','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXJIN', '6','税金','F','APGCTXP','STOREXSTHM',0,'1','25','6','税金','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'AMT', '8','货款金额','F','APGCTXP','STOREXSTHM',0,'1','26','8','货款金额','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'TAXAMT', '10','价税合计','F','APGCTXP','STOREXSTHM',0,'1','27','10','价税合计','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'MEMO', '20','备注','F','APGCTXP','STOREXSTHM',0,'1','28','20','备注','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME1', '50','自定义列1','F','APGCTXP','STOREXSTHM',0,'1','29','50','自定义列1','1')
  INSERT  SETCOL  (FEILDNAME,lEN,CHINESENAME,FABC,ProgramName,BILLNAME,HAVEGROUP,SHOWFLAG,ID,QSLEN,QSCHINESENAME,QSSHOWFLAG)    Values  ( 'USERNAME2', '50','自定义列2','F','APGCTXP','STOREXSTHM',0,'1','30','50','自定义列2','1')

----------ENDFLAG

update setcol   set showflag=0  where  feildname='ChangDu'
update setcol   set showflag=0  where  feildname='SpecNameD'

update setcol   set showflag=0  where  feildname='MAKEAREA'

update setcol   set  showflag=0  where  feildname='MODELNAME'

update setcol   set  showflag=0  where  feildname='MINPRICE'  or feildname='MOUTPRICE' or feildname='MEPRICE'

update setcol   set  showflag=0  where  feildname='LLZhongLiang'

update setcol   set showflag=0  where  feildname='USERNAME1' or feildname='USERNAME2'

update setcol   set showflag=0  where  feildname='Rate1' Or feildname='JianShu' OR feildname='lingtou'

update setcol   set  qsshowflag=showflag  

----------ENDFLAG
IF (SELECT VERSION FROM  ACCINFO  WHERE GUID='0001' ) < '7.5'  
BEGIN
    update GOODS SET  RATE=isnull(RATE,0)*1000  where isnull(RATE,0)<>0
END

----------ENDFLAG


UPDATE  ACCINFO SET VERSION='7.5'

----------ENDFLAG
